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) == 0 or len(A) == 1:
return len(A)
length = 1
pt = 1
n = len(A)
c = A[0]
count = 1
while pt < n:
if A[pt] == c:
if count == 1:
A[length] = A[pt]
elif count >= 2:
pt += 1
continue
count += 1
else:
c = A[pt]
count = 1
A[length] = A[pt]
pt += 1
length += 1
return length