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.
Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
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].
题目标签:Array, Two Pointers
题目给了我们一个nums array 和一个 k, 让我们找出有几对 相差k 的配对。
建立一个HashMap 把nums 的数字num 作为key 存入;把数字num 出现的 次数当作value 存入。
遍历map 的keys, 找 key + k 在map 里存不存在,存在的话说明这一对是k-diff pair。这种情况是当k 不等于 0;
当k = 0, 就要用到map 里的value 了,当key 出现的次数大于1 的时候, 至少2,那么 key 和 key 也是一对k-diff pair。
Java Solution:
Runtime beats 26.84%
完成日期:05/10/2017
关键词:Array, HashMap
关键点:把num当作key,把出现次数当作value 存入map,再遍历keys 来找k-diff pair
public class Solution
{
public int findPairs(int[] nums, int k)
{
int res = 0;
HashMap<Integer, Integer> map = new HashMap<>(); // set up the HashMap, key: number; value: occurrence.
for(int i=0; i<nums.length; i++)
{
// if map doesn't have it, add it into map and set value to 1.
// if map has it, increase it value by 1.
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1); } // iterate the map
for(Integer key: map.keySet())
{
if(k == 0 && map.get(key) > 1) // if k == 0 , only check it's value
res++;
else if(k > 0 && map.containsKey(key + k)) // if k > 0, check the map has (key + k) as a key
res++; } return res;
}
}
参考资料:
http://www.cnblogs.com/grandyang/p/6545075.html
LeetCode 题目列表 - LeetCode Questions List