力扣:532. 数组中的 k-diff 数对



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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值