给定一个整数数组和一个整数 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)。注意:
- 数对 (i, j) 和数对 (j, i) 被算作同一数对。
- 数组的长度不超过10,000。
- 所有输入的整数的范围在 [-1e7, 1e7]。
两种解法:
一种就是将元素存入map,数字对应出现的次数,如果k是0,就找出现次数大于2的,不然就遍历map拿出节点,再去map里找与其相差k的数。
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
if(k < 0){
return 0;
}
map<int,int> numMap;
for(auto x : nums){
numMap[x]++;
}
int count = 0;
map<int,int>::iterator it;
it = numMap.begin();
if(k == 0){
while(it != numMap.end()){
if(it->second >= 2){
count++;
}
it++;
}
}else{
while(it != numMap.end()){
if(numMap.count(it->first + k)){
count++;
}
if(numMap.count(it->first - k)){
count++;
}
numMap.erase(it++);
}
}
return count;
}
};
一种是双指针,先排序,然后一个指针遍历一个指针跑在后面找相差k的数,如果相差大于k说明没找到,前面的指针就前进。
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
int n = nums.size();
if(n<2 || k<0)
return 0;
sort(nums.begin(),nums.end());
int l = 0, r = 1;
int count = 0;
while(l<n && r< n){
if(nums[r] - nums[l] > k){
l++;
}
else if(nums[r] - nums[l] < k){
r++;
}
else{
count++;
l++;
while(l<n && nums[l] == nums[l-1])l++;
}
if(l>=r)
r = l+1;
}
return count;
}
};
本文探讨了在整数数组中查找k-diff数对的问题,即找出所有两数之差绝对值为k的整数对。介绍了两种解题方法:使用哈希映射和双指针技巧,通过示例详细解析了每种方法的实现步骤。
1439

被折叠的 条评论
为什么被折叠?



