Cover image for Interview Classic 150 Questions P26 Remove Duplicates from Sorted Array

Interview Classic 150 Questions P26 Remove Duplicates from Sorted Array


Timeline

Timeline

2025-09-28

init

std::unique

Title:

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;

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
nums.erase(std::unique(nums.begin(),nums.end()),nums.end());
return nums.size();
}
};

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
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
if (n == 0) {
return 0;
}
int fast = 1, slow = 1;
while (fast < n) {
if (nums[fast] != nums[fast - 1]) {
nums[slow] = nums[fast];
++slow;
}
++fast;
}
return slow;
}
};