LeetCode: K-diff Pairs in an Array
Problem:
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.
题意:
给定一个数组nums和一个数k,判断数组中有多少个组合使得两个数的差为给定的数k,不考虑顺序和重复的数字
方法:
如果k不等于零的话,那就是nums和nums数组每个数加k集合的交,如果k等于零的话,那就统计数组中相同的数字即可
代码:
1 import collections 2 class Solution(object): 3 def findPairs(self, nums, k): 4 """ 5 :type nums: List[int] 6 :type k: int 7 :rtype: int 8 """ 9 if k > 0: 10 return len(set(nums) & set(n + k for n in nums)) 11 elif k == 0: 12 return sum(v > 1 for v in collections.Counter(nums).values()) 13 else: 14 return 0

浙公网安备 33010602011771号