您的位置:首页 > 其它

[LeetCode] Remove Element 移除元素

2015-06-29 08:54 519 查看
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。代码如下:

class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int res = 0;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] != val) nums[res++] = nums[i];
}
return res;
}
};


LeetCode All in One 题目讲解汇总(持续更新中...)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: