Skip to content

Instantly share code, notes, and snippets.

@xiren-wang
Created September 1, 2014 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiren-wang/8a24a6ef048a8fa26950 to your computer and use it in GitHub Desktop.
Save xiren-wang/8a24a6ef048a8fa26950 to your computer and use it in GitHub Desktop.
remove duplicates in sorted array II: keep two copies only, but remove others.
class Solution {
public:
int removeDuplicates(int A[], int n) {
if (n <= 2)
return n;
int slow = 0;
int fast = slow + 1;
while (fast < n) {
// keep two copies
if (A[fast] == A[slow] ) {
//Note: must copy to slow+1, since it may hold OLD values.
A[slow+1] = A[fast];
slow ++;
fast ++;
}
while (fast < n && A[fast] == A[slow])
fast ++;
if (fast >= n)
break;
//now A[fast] != A[slow], copy and set it as new base element
A[slow+1] = A[fast];
slow = slow + 1;
fast ++;
}
return slow + 1;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment