Created
September 1, 2014 07:17
-
-
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.
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 <= 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