题目:
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,你需要找到数组中的 k-不同对的个数。这里的 k-不同对定义为一个数字对(i,j),其中 i 和 j 都是数组中的数字并且他们的绝对差是 k。
例子 1:
输入: [3, 1, 4, 1, 5], k = 2 输出: 2 解释: 这里的数组中有2-不同对,(1,3)和(3,5)。 尽管我们的输入中有2个1,我们应该只返回不同的对。
例子 2:
输入:[1, 2, 3, 4, 5], k = 1 输出: 4 解释: 这里的数组中有4个1-不同对,(1,2),(2,3),(3,4)和(4,5)。
例子 3:
输入: [1, 3, 1, 5, 4], k = 0 输出: 1 解释: 这里的数组中有1个0-不同对,(1,1)。
注意:
- 将(i,j)和(j,i)看成是相同的对。
- 数组的长度不超过10,000。
- All the integers in the given input belong to the range: [-1e7, 1e7].所有输入的数字在范围[-1e7,1e7]之间。
思路:
用map映射将数组中的数字和它们出现的次数进行映射,从头扫描map,当k=0时,只需要判断数组中的数字是否出现超过一次,若是,则结果result+1;当k>0时,若当前的数字i加上k还在map中,则满足绝对差为k,result+1。
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <map>
using namespace std;
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
map<int, int> m;
int res = 0;
for (int i = 0; i < nums.size(); i++) {
m[nums[i]]++;
}
for (auto a : m) {
if (k == 0 && a.second > 1)
res++;
if (k > 0 && m.count(a.first + k))
res++;
}
return res;
}
};
int main()
{
Solution s;
vector<int> nums = { 1,3,1,5,4 };
int k = 0;
int result = s.findPairs(nums, k);
cout << result << endl;
return 0;
}