Created
June 18, 2013 02:03
-
-
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].
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
| 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