import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* @author xnl
* @Description:数组中的 k-diff 数对
* @date: 2022/6/16 22:34
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {3, 1, 4, 1, 5};
System.out.println(solution.findPairs(nums, 2));
}
/**
* 使用set去重
* @param nums
* @param k
* @return
*/
public int findPairs2(int[] nums, int k) {
Set<Integer> set = new HashSet<>();
Set<Integer> res = new HashSet<>();
for (int num : nums) {
if (set.contains(num - k)){
res.add(num - k);
}
if (set.contains(num + k)){
res.add(num);
}
set.add(num);
}
return res.size();
}
/**
* 排序 加双指针
* @param nums
* @param k
* @return
*/
public int findPairs(int[] nums, int k) {
Arrays.sort(nums);
int res = 0;
for (int i = 0; i < nums.length; i++){
if (i == 0 || nums[i] != nums[i - 1]){
int j = i + 1;
// 如果i和j 的下标相同并且 下标j的值小于下标i的值加上k,证明这个不是我们想要的结果,继续找下一个
while (j < nums.length && nums[j] < nums[i] + k){
j++;
}
// 如果符合条件,记录结果
if (j < nums.length && nums[j] == nums[i] + k){
res++;
}
}
}
return res;
}
}
力扣:532. 数组中的 k-diff 数对
最新推荐文章于 2025-12-04 16:02:12 发布
该博客主要介绍了如何在Java中找到数组中差值为k的数对。提供了两种解决方案:一种是使用HashSet去重并查找,另一种是通过排序和双指针方法。这两种方法分别实现了查找过程,并在代码中进行了详细注释。
356

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



