Description:
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.
Note:
1.The pairs (i, j) and (j, i) count as the same pair.
2.The length of the array won't exceed 10,000.
3.All the integers in the given input belong to the range: [-1e7, 1e7].
Solution:
首先O(n^2)的算法无法通过本题,为了快速查找与每个数之差绝对值为k的数是否在数组中,可以考虑排序然后二分查找的方法,复杂度为O(nlogn)或者直接建立以数值为键,以出现次数为值建立字典,然后对字典每个键查找比它大k的数是否存在,因为一对数总有小有大,这样统计就不会重复,因为python的字典是hash table实现的,所以复杂度是O(n),这题还有2个坑,一个是k<0的情况,直接return 0,还有一个是k=0的情况,要查看字典每个键的值是否>1,若>1,答案加1,代码如下:
class Solution():
def findPairs(self, nums, k):
if k<0:
return 0
num2={
}
res=0
n=len(nums)
for number in nums:
l=num2.get(number,0)
num2[number]=l+1
if k==0:
for number in num2.keys():
if num2[number]>1:
res=res+1
else:
for number in num2.keys():
if num2.get(number+k,0)>0:
res=res+1
return res