【LeetCode】532. K-diff Pairs in an Array

版权声明:本文为博主原创文章,请尊重原创,转载请注明原文地址和作者信息! https://blog.csdn.net/zzc15806/article/details/82415275

class Solution:
    # 对k=0和k!=0分别做判断
    def findPairs(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        from collections import Counter
        
        if k == 0:
            return sum([i>1 for i in Counter(nums).values()])
        elif k > 0:
            return len(set(nums) & set([i+k for i in nums]))
        else:
            return 0


class Solution:
    # 通过bool运算区分k=0和k!=0
    def findPairs(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        from collections import Counter
        c = Counter(nums)
        
        if k < 0:
            return 0
        else:
            return sum(c[i+k] > 1-bool(k) for i in c.keys())    

猜你喜欢

转载自blog.csdn.net/zzc15806/article/details/82415275