[LeetCode][Python]26. Remove Duplicates from Sorted Array

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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,949评论 0 23
  • 繁重的高中生活终于结束,迎接而来的是时长三个月的暑假,而如何让人卸下沉重的包袱,享受这段来之不易的时光我想旅行是一...
    松月其阅读 328评论 0 2
  • 我模模糊糊的听到孩子们的吵闹,可一直睁不开眼,翻来覆去的继续睡,我还没有洗脸,桌上的餐盘还没有收拾,再不洗会有很多...
    NutsVicky阅读 162评论 0 1
  • 她在上海读研 他在伦敦留洋 他们天各一方 头顶一个月亮 他是民航机长 她是舞蹈演员 他今晚在航线 她今晚在排练 他...
    禅小喵阅读 348评论 0 0