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), whereiandjare both numbers in the array and their absolute difference is k.
Example 1:
Example 2:
Example 3:
Note:
The pairs (i, j) and (j, i) count as the same pair.
The length of the array won't exceed 10,000.
All the integers in the given input belong to the range: [-1e7, 1e7].
这题可以用hashmap来做到O(n)时间复杂度。这题是看了discuss里大神的做法写的。首先我们统计每一个数出现的次数。然后,我们loop through这个map,边loop边找diff。这里diff是k,如果k = 0的情况,其实是找两个相同的数,我们只要看到entry里有两个或以上的数时就把count+1.(因为不算重复的)。另一种情况是找diff = k的,如果在hashmap里找到key + k的话,证明我们找到一对了。所以count++。不用算key - k因为不算重复的。
Last updated