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].
這道題給了我們一個含有重復數字的無序數組,還有一個整數k,讓找出有多少對不重復的數對 (i, j) 使得i和j的差剛好為k。由於k有可能為0,而只有含有至少兩個相同的數字才能形成數對,那么就是說需要統計數組中每個數字的個數。可以建立每個數字和其出現次數之間的映射,然后遍歷 HashMap 中的數字,如果k為0且該數字出現的次數大於1,則結果 res 自增1;如果k不為0,且用當前數字加上k后得到的新數字也在數組中存在,則結果 res 自增1,參見代碼如下:
解法一:
class Solution { public: int findPairs(vector<int>& nums, int k) { int res = 0, n = nums.size(); unordered_map<int, int> m; for (int num : nums) ++m[num]; for (auto a : m) { if (k == 0 && a.second > 1) ++res; if (k > 0 && m.count(a.first + k)) ++res; } return res; } };
下面這種方法沒有使用 HashMap,而是使用了雙指針,需要給數組排序,節省了空間的同時犧牲了時間。遍歷排序后的數組,然后在當前數字之前找最后一個和當前數之差大於k的數字,若這個數字和當前數字不是同一個位置,且和上一輪 pre 不是同一個數字,且和當前數字之差正好為k,那么結果 res 自增1,然后將 pre 賦值為這個數字,參見代碼如下:
解法二:
class Solution { public: int findPairs(vector<int>& nums, int k) { int res = 0, n = nums.size(), j = 0, pre = INT_MAX; sort(nums.begin(), nums.end()); for (int i = 1; i < n; ++i){ while (j < i && nums[i] - nums[j] > k) ++j; if (j != i && pre != nums[j] && nums[i] - nums[j] == k) { ++res; pre = nums[j]; } } return res; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/532
類似題目:
Minimum Absolute Difference in BST
參考資料:
https://leetcode.com/problems/k-diff-pairs-in-an-array/submissions/
https://leetcode.com/problems/k-diff-pairs-in-an-array/discuss/100104/two-pointer-approach