problem:
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]
.
solution:
法一
class Solution:
# @param A a list of integers
# @return an integer
def removeDuplicates(self,A):
n = len(A)
if n ==0 :
return 0
index = 0
times = 0
for i in xrange(n):
if A[index] == A[i]:
times += 1
if times ==2 :
index += 1
A[index] = A[i]
else:
index += 1
A[index] = A[i]
times = 1
A = A[:index+1]
return len(A)
法二
class Solution:
# @param A a list of integers
# @return an integer
def removeDuplicates(self,A):
n = len(A)
if n <= 2 :
return n
index = 2
for i in xrange(2,n):
if A[i] != A[index-2]:
A[index] = A[i]
index += 1
A = A[:index]
return len(A)