Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
typedef vector<int>::iterator it;
it i = nums.begin();
it j = nums.end();
while (i != j) {
while (i != j && *i != val) ++i;
if (i == j) break;
--j;
while (i != j && *j == val) --j;
if (i != j) *i = *j;
}
nums.erase(j, nums.end());
return nums.size();
}
}; // runtime contribution 64.8%
hehe
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
nums.erase(remove(nums.begin(), nums.end(), val), nums.end());
return nums.size();
}
}; // runtime contribution 10.05%
参考后
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
typedef vector<int>::size_type sz;
sz size = nums.size();
for (sz i = 0; i < size;) {
if (nums[i] == val) {
nums[i] = nums[size - 1];
--size;
}else
++i;
}
nums.erase(nums.begin() + size, nums.end());
return size;
}
}; // runtime contribution 64.8%