美文网首页
【Leetcode】【Python】532. K-diff Pa

【Leetcode】【Python】532. K-diff Pa

作者: 小歪与大白兔 | 来源:发表于2017-12-23 22:44 被阅读0次

    问题描述:

    image.png

    代码示例一:

    import collections
    class Solution(object):
        def findPairs(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: int
            """
            c = collections.Counter(nums)                         
            if k < 0 : return 0                       
            elif k > 0:                               
                return len(set(nums) & set(n+k for n in nums))
            elif k == 0:                              
                return  sum(n>1 for n in c.values())  
    

    collections模块下的Counter:

    Counter是一个简单的计数器,例如,统计字符出现的个数:
    nums=[3, 1, 4, 1, 5]
    c = collections.Counter(nums)
    print c
    输出结果如下:
    Counter({1: 2, 3: 1, 4: 1, 5: 1})

    补充知识:

    Python拥有一些内置的数据类型,比如str, int, list, tuple, dict等, collections模块在这些内置数据类型的基础上,提供了几个额外的数据类型:
    namedtuple(): 生成可以使用名字来访问元素内容的tuple子类
    deque: 双端队列,可以快速的从另外一侧追加和推出对象
    Counter: 计数器,主要用来计数
    OrderedDict: 有序字典
    defaultdict: 带有默认值的字典

    参考链接:http://www.zlovezl.cn/articles/collections-in-python/

    相关文章

      网友评论

          本文标题:【Leetcode】【Python】532. K-diff Pa

          本文链接:https://www.haomeiwen.com/subject/gjccgxtx.html