题目:
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.
思路:
用两个指针来实现,第一个指针记录不与给定元素相同的个数,第二个用来遍历整个数组。
时间复杂度:O(n)
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int begin=0,n=nums.size();
for(int i=0;i<n;i++) if(nums[i]!=val) nums[begin++]=nums[i];
return begin;
}
};