Tuesday, June 10, 2014

Remove Duplicates from Sorted Array II (Python + Java)

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].


/*
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;
}
}
"""
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