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 by modifying the input array in-place with O(1) extra memory.
Example:
Given nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
给出一个经排序后的数组,去重,并返回去重后的数组长度。
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = 0
while(1):
if n+1 >= len(nums):
return len(nums)
elif nums[n] == nums[n+1]:
del nums[n+1]
else:n+=1
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = 0
while(1):
if n+1 >= len(nums):
return len(nums)
elif nums[n] == nums[n+1]:
del nums[n+1]
else:n+=1
方法二:
也可以用python的内置函数set,在python中list内部的元素是有序的,可重复的,set是无序的,不可重复的。
newnums = list(set(nums))
return len(newnums)
方法三:
用于列表的去重,用到dictionary。
newnums = []
dict = {}
for i in range(len(nums)):
if nums[i] not in dict:
dict[nums[i]] = 'exist'
newnums.append(nums[i])
return len(newnums)