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 数对
最新推荐文章于 2024-10-14 18:52:56 发布