Remove Duplicates from Sorted Array II
Source
- lintcode: Remove Duplicates from Sorted Array II
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].
Python
class Solution:
"""
@param A: a list of integers
@return an integer
"""
def removeDuplicates(self, A):
# write your code here
if A is None or len(A)==0:
return 0
slow=0
fast=1
count=1
while fast<len(A):
if A[fast]==A[slow] and count<2:
slow+=1
A[slow]=A[fast]
fast+=1
count+=1
elif A[fast]!=A[slow]:
slow+=1
A[slow]=A[fast]
fast+=1
count=1
else:
fast+=1
# while fast<len(A):
# if A[fast]==A[slow] and count>=2:
# fast+=1
# else:
# tmp1 = slow
# tmp2 = fast
# slow+=1
# A[slow]=A[fast]
# fast+=1
# if A[tmp2]==A[tmp1]:
# count+=1
# else:
# count=1
return slow+1