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) { // Start typing your Java solution below // DO NOT write main() function if(A == null) return 0; if(A.length <=1 )return A.length; int len = A.length; int i = 0; int value = A[0]; int time = 1; while(i< len-1){ if(value == A[i+1]){ time++; if(time<=2){ i++; } else{ for(int j = i ; j<len-1;j++){// len-1!!! A[j] = A[j+1]; } len--; } } else{ i++; time = 1; value = A[i]; } } return len; } }
mistakes: remove dup from array, the lenth is j< len-1 due to array removed one element
class Solution: # @param a list of integers # @return an integer def removeDuplicates(self, A): if len(A) == 0: return 0 if len(A) == 1: return 1 dup = False index = 0 for i in A[1:]: if i != A[index]: index = index + 1 A[index] = i dup = False elif dup == False : index = index + 1 A[index] = i dup = True return index+1