LeetCode Python 532 K-diff Pairs in an Array

Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

Example:

Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.

Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).

Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
  • 数组里有没有那么几对数,他们之间相差k。
class Solution(object):
    def findPairs(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if k>0:
            return len(set(nums) & set(n+k for n in nums))
        elif k==0:
            return sum(v>1 for v in collections.Counter(nums).values())
        else:
            return 0

  • set()给我带来喜悦,因为他可以去重(chong)。
  • 此外,set()还有一些小运算:
>>> a = set('shengfaji')
>>> b = set('kuaileshui')
>>> a
set(['a', 'e', 'g', 'f', 'i', 'h', 'j', 'n', 's'])
>>> a-b                               # 只在a中存在的元素(差集)
set(['n', 'j', 'g', 'f'])
>>> a|b                               # a与b的并集
set(['a', 'e', 'g', 'f', 'i', 'h', 'k', 'j', 'l', 'n', 's', 'u'])
>>> a&b                               # a与b的交集
set(['a', 'i', 's', 'e', 'h'])
>>> a^b                               # a与b的对称差((a|b)-(a&b))
set(['g', 'f', 'k', 'j', 'l', 'n', 'u'])
>>>
  • Counter给我带来喜悦,因为她计数真的很方便.
  • 代码return sum(v>1 for v in collections.Counter(nums).values())作用同下:
flag=0
for v in collections.Counter(nums).values():
    if v>1:
        flag+=1
return flag
  • 一般情况下用集合nums&集合nums+k即可解决问题。
  • 但是在k=0这种自恋情况下,就只能数数了。
  • 综合起来,set和Counter这两份喜悦相互重叠,就能得到了梦幻一般的幸福时光。

猜你喜欢

转载自blog.csdn.net/weixin_41084236/article/details/81179503