This problem is to remove all instances equal to a given value, called 'val', in the array. The array could be out of order.
Solution:
We know that in the end we would have every element that's not equal to val in the array. How would we put those elements? Suppose we have 3,3,3,3,1,2,4,3,5, and val = 3. The final result should be 1,2,4,5. Note that before we meet 1, we have 4 3s, this means if we remove those 3s, 1 is going to be shifted to left by 4 steps. also 2, 4 should be shifted by 4 steps. For 5, there are 5 3s before it, and thus 5 should be shifted to left by 5 steps. Now we can see that, we should shift the element not equal to val by the number of val at its left. So we scan through the array, and keep counting how many val we have met. Once we have that count, we could shift every element correctly.
Code:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int shift = 0;
for(int i = 0; i < nums.size(); i ++){
if(nums[i] == val) shift++;
else{
nums[i-shift] = nums[i];
}
}
return nums.size() - shift;
}
};