您的位置:首页 > 其它

27. Remove Element

2016-03-09 23:55 375 查看
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.

题意:去除数组中的所有val值,返回数组的新长度。

思路:注意对题意的理解,题意说不关心超出长度之后的数值,则思路是把所val值依次往后置换,然后返回置换后的索引+1。

class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int p, q;
p = 0;
q = nums.size() - 1;
while (p <= q){
if (nums[p] == val){
nums[p] = nums[q];
nums[q] = val;
q--;
}
else{
p++;
}
}
return q + 1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: