i) to track the last unique element and another (j) to find new unique ones.i. This way, duplicates get overwritten while keeping the order intact.i at index 0 and j at index 1.j, comparing nums[i] with nums[j].nums[j] is different from nums[i], increment i and update nums[i] with nums[j].i + 1.Here’s the code:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n=nums.size();
int i=0;
for(int j=1;j<n;j++)
{
if(nums[i]!=nums[j]){
i++;
nums[i]=nums[j];
}
}
return i+1;
}
};
i and j) to traverse the array:
i tracks the position of the last unique element.j iterates through the array to find the next unique element.Feel free to share your approach and feedback in comment box.