[InterviewBit] Remove Duplicates from Sorted Array II

Remove Duplicates from Sorted Array II

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
int Solution::removeDuplicates(vector<int> &A) {
int res = 0, l = 2, r = 2, n = A.size();
if(n < 3) return n;
while(r < n) {
if(A[r] != A[l-2]) A[l++] = A[r];
r++;
}
return l;
}

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int Solution::removeDuplicates(vector<int> &A) {
int res = 0, l = 0, r = 0, n = A.size();
while(l < n) {
if(l and A[l-1] == A[l]) l++;
else if(l + 1 < n and A[l] != A[l+1]) l++;
else {
r = l + 2;
while(r < n and A[r] == A[l]) res += 1, r += 1;
for(int i = l + 2, j = r; j < n; j++,i++) {
A[i] = A[j];
}
n -= (r - (l + 2));
l += 2;
}
}
return A.size() - res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/27/PS/interviewbit/remove-duplicates-from-sorted-array-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.