Skip to content

Instantly share code, notes, and snippets.

@xiren-wang
Last active August 29, 2015 14:05
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/9384b15c2e3cc4461567 to your computer and use it in GitHub Desktop.
Save xiren-wang/9384b15c2e3cc4461567 to your computer and use it in GitHub Desktop.
remove duplicates in sorted array. Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. For example, Given input array A = [1,1,2], Your function should return length = 2, and A is now …
class Solution {
public:
int removeDuplicates(int A[], int n) {
if (n <= 0) //necessary, since slow is baed on 0 as in next
return n;
//two pointers, one slow, one fast
// sweep fast if A[fast ] == A[slow]
// if new element found, keep it, set as new base element
int moveToLeft = 0;
int slow = 0;
int fast = slow + 1;
while (fast < n) {
//skip same values with slow
while (fast < n && A[fast] == A[slow] )
fast ++;
if (fast >= n)
break;
//now A[fast] != A[slow], copy to A[slow+1]
A[slow+1] = A[fast];
//new base as in A[slow+1]
slow = slow + 1;
fast ++; //fast should be always faster than slow
}
return slow + 1;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment