Given an array of integers
nums
and an integerk
, return the number of unique k-diff pairs in the array.A k-diff pair is an integer pair
(nums[i], nums[j])
, where the following are true:
0 <= i < j < nums.length
|nums[i] - nums[j]| == k
Notice that
|val|
denotes the absolute value ofval
.
class Solution:
def findPairs(self, nums, k):
# 记录匹配的元组
temp = set()
# 从大到小排序 (使 a > b): a - b == k --> a - k == b
nums = sorted(nums, reverse=True)
# 用字典记录:d = {a - k : a} (d[a - k] = a)
d = {}
for each in nums:
# 即 b == a - k
if each in d.keys():
# 记录下这组 (b, a)
temp.add((each, d[each]))
d[each - k] = each
return len(temp)