0

I was doing this leetcode question of removing duplicates from sorted vector and return new size of vector, I came up with obvious simple approach to remove duplicates. but during my time of answering the question i found out erase() invalidate the itrator after deletion. but why i used this code it got accepted and i ran it on some other online compilers with some test cases and it also worked there. i don't understand why i can use previously initialized itrator even though it should be invalidated.

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size()==0)
        {
            return 0;
        }
       for(auto i=nums.rend()-1;i>nums.rbegin();i--)
       {
           int seclast=*(i-1);
           if(seclast==*i)
           {
               nums.erase(i);
               // i--;
           }
       }
       return nums.size();
    }
};
4

0 回答 0