给定一个整数数组和一个整数 k, 你需要在数组里找到不同的 k-diff 数对。这里将 k-diff 数对定义为一个整数对 (i, j), 其中 i 和 j 都是数组中的数字,且两数之差的绝对值是 k.
示例 1:
输入: [3, 1, 4, 1, 5], k = 2
输出: 2
解释: 数组中有两个 2-diff 数对, (1, 3) 和 (3, 5)。
尽管数组中有两个1,但我们只应返回不同的数对的数量。
示例 2:
输入:[1, 2, 3, 4, 5], k = 1
输出: 4
解释: 数组中有四个 1-diff 数对, (1, 2), (2, 3), (3, 4) 和 (4, 5)。
示例 3:
输入: [1, 3, 1, 5, 4], k = 0
输出: 1
解释: 数组中只有一个 0-diff 数对,(1, 1)。
思路:这个题可以借助一个map来做,用map存储值和对应的索引,然后再遍历一次,寻找map中有没有满足nums[i]+k的键值,为什么呢,因为k始终都是其中两个数相减的绝对值的结果,如果满足条件,其中一个加上k就肯定会找到另外一个。但是还需判断一下找到的键值是不是它本身,假如k为0,则就要排除这种情况,最后还要在map中移除这个值,避免一个K-diff对出现两次及以上。
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
if(k<0)
return 0;
map<int,int> mapMatchIndex;
int nCount = nums.size();
int nRes = 0;
for(int i=0;i<nCount;i++)
{
mapMatchIndex[nums[i]] = i;
}
for(int i=0;i<nCount;i++)
{
if(mapMatchIndex.find(nums[i]+k)!=mapMatchIndex.end() && mapMatchIndex[nums[i]+k]!=i)
{
nRes++;
mapMatchIndex.erase(nums[i]+k);
}
}
return nRes;
}
};