std::unique is a C++function in C++. It does not actually delete elements from the container, but moves adjacent duplicate elements to the back, and returns an iterator pointing to the new logical end. Combined with erase, it can remove duplicate elements.
1 2 3 4 5 6 7 8 9 10 11
#include<algorithm> #include<vector> using std::vector;
Classic fast and slow pointer solution: the fast pointer indicates the index position reached during array traversal, and the slow pointer indicates the index position where the next different element should be placed. Initially, both pointers point to index 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intremoveDuplicates(vector<int>& nums){ int n = nums.size(); if (n == 0) { return0; } int fast = 1, slow = 1; while (fast < n) { if (nums[fast] != nums[fast - 1]) { nums[slow] = nums[fast]; ++slow; } ++fast; } return slow; } };