问题:Givenan array and a value, remove all instances of that value in place and returnthe new length.Do not allocate extra space for another array, you must do thisin place with constant memory.The order of elements can be changed. It doesn'tmatter what you leave beyond the new length.Example:Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2,with the first two elements of nums being 2.
删去数组里指定值元素,不能创建另一个数组,因为是in place。
思考:还是两个游标,i和j,如果当前元素值与要删除的指定值不同,则将此值赋给j游标代表的值,同时使j加1。
代码:classSolution {
public:
int removeElement(vector<int>& nums, int val) {
int j=0;
int l=nums.size();
for (int i=0;i<l;i++){
if(nums[i]!=val){
nums[j]=nums[i];
j=j+1;
}
}
return j;
}
};