Created
November 11, 2013 17:21
-
-
Save charlespunk/7416855 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
Follow up for "Remove Duplicates": | |
What if duplicates are allowed at most twice? | |
For example, | |
Given sorted array A = [1,1,1,2,2,3], | |
Your function should return length = 5, and A is now [1,1,2,2,3]. |
This file contains hidden or 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
public class Solution { | |
public int removeDuplicates(int[] A) { | |
// IMPORTANT: Please reset any member data you declared, as | |
// the same Solution instance will be reused for each test case. | |
if(A.length == 0) return 0; | |
int dChance = 1; | |
int writer = 0; | |
int reader = 1; | |
int chance = dChance; | |
while(reader != A.length){ | |
if(A[reader] == A[writer]){ | |
if(chance > 0){ | |
chance--; | |
A[++writer] = A[reader++]; | |
} | |
else{ | |
reader++; | |
} | |
} | |
else{ | |
A[++writer] = A[reader++]; | |
chance = dChance; | |
} | |
} | |
return writer + 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment