描述:
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length
(1)现在考虑数组包含很少的要删除的元素的情况。例如,num=[1,2,3,5,4],Val=4。之前的算法会对前四个元素做不必要的复制操作。另一个例子是 num=[4,1,2,3,5],Val=4。似乎没有必要将 [1,2,3,5这几个元素左移一步
(2) val = 4
while( i < j )
(3)如果nums[i] != val,
i ++;
(4)如果 nums[i] = val
则 nums[i] = nums[j]
扫描二维码关注公众号,回复:
9845487 查看本文章
然后j--;
(5)while( i < j )不成立,从而跳出循环
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
/**
* @brief remove Element
* @date:2020-1-14
*/
class Solution{
public:
int RemoveElement(vector<int> &nums,int val){
int j=0;
for(int i=0;i<nums.size();i++){
if(nums[i]!=val)
nums[j++]=nums[i];
}
return j;
}
};
class soluton2{
public:
int RemoveElement2(vector<int>& nums,int val){
int j=nums.size();
int i=0;
while(i<j){
if(nums[i]==val)
nums[i]=nums[--j];
else
++i;
}
return j;
}
};
void display(const int & data)
{
cout<<data<<' ';
}
int main(int argc, char *argv[])
{
int a[]={1,0,-1,0,-2,2};
vector<int> vec(a,a+sizeof(a)/sizeof(int));
for_each(vec.begin(),vec.end(),display);
cout<<endl;
Solution s1;
soluton2 s2;
// int result=s1.RemoveElement(vec,1);
int result2=s2.RemoveElement2(vec,1);
// cout<<result<<endl;
cout<<result2<<endl;
return 0;
}