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.
分析:
双指针遍历,cnt始终指向当前元素以前不为val的元素序列
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int cnt=0;
for (int i = 0; i<nums.size(); i++)
if(nums[i] != val)
nums[cnt++] = nums[i];
return cnt;
}
};
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.youkuaiyun.com/ebowtang/article/details/50448834
原作者博客:http://blog.youkuaiyun.com/ebowtang