classSolution{public:intremoveDuplicates(vector<int>&nums){// We create a `set`, cause it will store only the unique elementsset<int>uniqueElements;// We loop from start to end in our `nums` array// And insert each element, (the `set` will ignore the duplicates)for(intnum:nums){uniqueElements.insert(num);}// After that, we get the size of the `uniqueElements`// It is the number of unique elementsintk=uniqueElements.size();// We copy back the unique elements from beginning in our original arrayintindex=0;for(intuniqueNum:uniqueElements){nums[index]=uniqueNum;index++;}returnk;// Just return the number of unique elements, as the problem requires}};
classSolution{public:intremoveDuplicates(vector<int>&nums){intn=nums.size();// If the array is empty, no unique elementsif(nums.empty()){return0;}// This is out `writerPointer` it will show the place, where we have to put the next unique number// It will also count the number of unique elements (the answer)intk=1;// it will go from (index 1) till end of the arrayfor(inti=1;i<n;i++){// If current number `i` is different from last, unique number we have seen `k - 1`if(nums[i]!=nums[k-1]){nums[k]=nums[i];// If it is different, we will overwrite the last, duplicate elementk++;// And move the `k` pointer forward, cause that position has a unique number now}// else if it is a duplicate, we ignore it}returnk;}};
Warning
LINK
You are about to visit a link which has been flagged with the above content warnings. Do you wish to continue?