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 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.
思路:
Python中有个collections模块,它提供了个类Counter,用来跟踪值出现了多少次。注意key的出现顺序是根据计数的从大到小。使用它的items()方法可以拿到key,即为唯一的元素。
还有An OrderedDict is a dictionary subclass that remembers the order in which its contents are added.
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
import collections
return len([n for n, count in collections.Counter(nums).items()])
def removeDuplicates2(self, nums):
import collections
nums[:] = collections.OrderedDict.fromkeys(nums)
# print nums
return len(nums)