- tags: LeetCode101,In-place
Travel array in reverse order, and record how many times need to swap, which is how many elements not equal val.
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int k = 0;
for (int j = nums.size() - 1; j >= 0; --j) {
if (nums[j] == val) {
for (int i = 0; i < k; ++i) {
swap(nums[i + j], nums[j + i + 1]);
}
} else {
k++;
}
}
return k;
}
};