Last active
August 29, 2015 14:05
-
-
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 …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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