0

Their input is [0,1,2,2,3,0,4,2] 2 My Output: [0,1,2,3,0,4] Expected: [0,1,4,0,3]

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        
        for( int i = 0; i < nums.size(); i ++){
            int j = i;
            if (nums[j] == val){
                nums.erase( nums.begin() + j);
            }
        }
        
        return nums.size();
        
    }
};
  • 3
    Do you still want to advance `i` after doing this `nums.erase( nums.begin() + j);`? You remove an element then skip the next value because it moves to the same index as the removed element. – drescherjm Dec 06 '20 at 20:15
  • You should take a look at the [erase-remove-idiom](https://stackoverflow.com/questions/347441/erasing-elements-from-a-vector). It should be more efficient than erasing each element individually. – Lukas-T Dec 06 '20 at 20:21
  • What is the logic that converts the input to the output? – cigien Dec 06 '20 at 20:21
  • Draw a picture. Draw the contents of the vector at the end of each iteration of the loop. At that point, the answer will become clear. – Marshall Clow Dec 06 '20 at 20:39

0 Answers0