Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
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 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]. | |
*/ | |
public class Solution { | |
public int removeDuplicates(int[] A) { | |
if (A==null){ | |
return 0; | |
} | |
if (A.length<3){ | |
return A.length; | |
} | |
int temp=A[1]; | |
int len=1; | |
for(int i=2; i<A.length; i++){ | |
if (A[i]!=A[i-2]){ | |
A[len++]=temp; | |
temp=A[i]; | |
} | |
} | |
A[len++]=temp; | |
return len; | |
} | |
} |
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
""" | |
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]. | |
""" | |
class Solution: | |
# @param A a list of integers | |
# @return an integer | |
def removeDuplicates(self, A): | |
if len(A)<3: | |
return len(A) | |
temp=A[1] | |
length=1 | |
for i in range (2, len(A)): | |
if A[i]!=A[i-2]: | |
A[length]=temp | |
length+=1 | |
temp=A[i] | |
A[length]=temp | |
length+=1 | |
return length |
No comments:
Post a Comment