您的位置:首页 > 其它

[Leetcode] Remove Element

2015-08-12 14:00 176 查看
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.

class Solution {
public:
/*algorithm
use two pointer: i pointer to source array, j point to dest array
copy i element to j array when i element is not val
time O(n), space O(1)
*/
int removeElement(vector<int>& nums, int val) {
int n = nums.size();
int j = 0,i = 0;
while(i < n){
if(nums[i] != val)nums[j++] = nums[i++];
else i++;
}
return j;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法