LeetCode 532. K-diff Pairs in an Array (在数组中相差k的配对)

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:

  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].

 


 

题目标签: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

 1 public class Solution 
 2 {
 3     public int findPairs(int[] nums, int k) 
 4     {
 5         int res = 0;
 6         HashMap<Integer, Integer> map = new HashMap<>();
 7         
 8         // set up the HashMap, key: number; value: occurrence.
 9         for(int i=0; i<nums.length; i++)
10         {
11             // if map doesn't have it, add it into map and set value to 1.
12             // if map has it, increase it value by 1.
13             map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
14             
15         }
16         
17         // iterate the map
18         for(Integer key: map.keySet())
19         {
20             if(k == 0 && map.get(key) > 1)    // if k == 0 , only check it's value
21                 res++;
22             else if(k > 0 && map.containsKey(key + k))    // if k > 0, check the map has (key + k) as a key  
23                 res++;
24                 
25         }
26 
27         return res;
28     }
29 }

参考资料:

http://www.cnblogs.com/grandyang/p/6545075.html

 

LeetCode 题目列表 - LeetCode Questions List

 

posted @ 2017-09-26 06:16  Jimmy_Cheng  阅读(309)  评论(0编辑  收藏  举报