problem:
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A = [1,1,2]
,
Your function should return length = 2
, and A is now [1,2]
.
class Solution:
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
if len(A) == 0:
return 0
n = len(A)
index = 0
for i in xrange(n):
if A[index] != A[i]:
index += 1
A[index] = A[i]
A = A[:index+1]
return len(A)
解法二;
利用python数据结构set的去重功能,但是之后要对A排序。
class Solution:
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
A = list(set(A))
A.sort()
return len(A) #注意题目要求 A 并不是乱序的 set(A)会导致在形成list后是乱序的