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), 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].
讲道理跟Two Nums很像,可惜没出方法,用了个比较土的方法,第二个参考的方法会贴上类似Two Nums的方法
1 class Solution { 2 public: 3 int findPairs(vector<int>& nums, int k) { 4 5 if(k < 0) 6 return 0; 7 8 multiset<int> s(nums.begin(), nums.end()); 9 //int n = nums.size(); 10 int count = 0; 11 12 if(k == 0) 13 { 14 for (auto n : s) 15 { 16 if (s.count(n) >= 2) 17 { 18 ++count; 19 s.erase(n); 20 } 21 } 22 } 23 if (k == 0) 24 return count; 25 26 set<int> t(nums.begin(), nums.end()); 27 for (auto n : t) 28 { 29 int target = n + k; 30 31 if (t.find(target) != t.end()) 32 { 33 34 ++count; 35 } 36 } 37 38 return count; 39 } 40 };
法二:
1 class Solution { 2 public: 3 /** 4 * for every number in the array: 5 * - if there was a number previously k-diff with it, save the smaller to a set; 6 * - and save the value-index to a map; 7 */ 8 int findPairs(vector<int>& nums, int k) { 9 if (k < 0) { 10 return 0; 11 } 12 unordered_set<int> starters; 13 unordered_map<int, int> indices; 14 for (int i = 0; i < nums.size(); i++) { 15 if (indices.count(nums[i] - k)) {//target1 16 starters.insert(nums[i] - k); 17 } 18 if (indices.count(nums[i] + k)) {//target2 19 starters.insert(nums[i]); 20 } 21 22 indices[nums[i]] += 1; 23 } 24 25 return starters.size(); 26 } 27 };