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;
}
};