Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlespunk/7416855 to your computer and use it in GitHub Desktop.
Save charlespunk/7416855 to your computer and use it in GitHub Desktop.
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].
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