Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save luoxiaoxun/5802104 to your computer and use it in GitHub Desktop.

Select an option

Save luoxiaoxun/5802104 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].
C++:
class Solution {
public:
int removeDuplicates(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n==0||n==1) return n;
int min=A[0]-1;
int cur=A[0];
int count=0;
for(int i=0;i<n;i++){
if(A[i]==cur){
count++;
if(count>2) A[i]=min;
}else{
count=1;
cur=A[i];
}
}
int index=0;
for(int i=0;i<n;i++)
if(A[i]!=min)
A[index++]=A[i];
return index;
}
};
Java:
public class Solution {
public int removeDuplicates(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
int n=A.length;
if(n==0||n==1) return n;
int min=A[0]-1;
int cur=A[0];
int count=0;
for(int i=0;i<n;i++){
if(A[i]==cur){
count++;
if(count>2) A[i]=min;
}else{
count=1;
cur=A[i];
}
}
int index=0;
for(int i=0;i<n;i++)
if(A[i]!=min)
A[index++]=A[i];
return index;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment