题目:
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.
分析:
- 异常判断:k是绝对值,意味着k为非负
- 特例:集合为空,k-diff对数量为0
- k=0,寻找列表中数量大于1的值,采用了Counter类,使用唯一元素的数量减去列表中唯一的元素数量
- k>0,建立与原列表差值为k的列表,计算该列表与原列表交集中元素个数
代码:
from collections import Counter
class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if not nums or k < 0:
return 0
if k == 0:
temp = zip(*(Counter(nums).items()))
return len(set(nums)) - Counter(temp[1])[1]
lMinus = map(lambda x:x - k,nums)
return len(set(lMinus) & set(nums))
思考:
- 与之前两元素和为k不同,无需排除k/2的情况
- 在讨论区看到了一个思路类似,简洁很多的代码,来自leetcode的lee215,代码如下:
def findPairs(self, nums, k):
c = collections.Counter(nums)
return sum(k > 0 and i + k in c or k == 0 and c[i] > 1 for i in c)