美文网首页leetcode算法
532. 数组中的 k-diff 数对

532. 数组中的 k-diff 数对

作者: 刘翊扬 | 来源:发表于2022-06-16 23:35 被阅读0次

    给你一个整数数组 nums 和一个整数 k,请你在数组中找出 不同的 k-diff 数对,并返回不同的 k-diff 数对 的数目。

    k-diff 数对定义为一个整数对 (nums[i], nums[j]) ,并满足下述全部条件:

    0 <= i, j < nums.length
    i != j
    nums[i] - nums[j] == k
    注意,|val| 表示 val 的绝对值。

    示例 1:

    输入:nums = [3, 1, 4, 1, 5], k = 2
    输出:2
    解释:数组中有两个 2-diff 数对, (1, 3) 和 (3, 5)。
    尽管数组中有两个 1 ,但我们只应返回不同的数对的数量。
    

    示例 2:

    输入:nums = [1, 2, 3, 4, 5], k = 1
    输出:4
    解释:数组中有四个 1-diff 数对, (1, 2), (2, 3), (3, 4) 和 (4, 5) 。
    

    示例 3:

    输入:nums = [1, 3, 1, 5, 4], k = 0
    输出:1
    解释:数组中只有一个 0-diff 数对,(1, 1) 。

    提示:

    • 1 <= nums.length <= 104
    • -107 <= nums[i] <= 107
    • 0 <= k <= 10

    自己的写法

    class Solution {
        public int findPairs(int[] nums, int k) {
            Arrays.sort(nums);
            int n = nums.length, ans = 0;
            for (int i = 0; i < n; i++) {
                boolean flag = false;
               // 相同的直接跳过
                while (i + 1 < n && nums[i] == nums[i + 1]) {
                    i++;
                    flag = true;
                }
                // 如果k = 0,相同的数, ans++
                if (flag && k == 0) {
                    ans++;
                }
                for (int j = i + 1; j < n; j++) {
                    while (j + 1 < n && nums[j] == nums[j + 1]) {
                        j++;
                    }
                    if (nums[j] - nums[i] == k) {
                        ans++;
                    }
                }
            }
            return ans;
        }
    }
    

    哈希

    image.png
    public int findPairs(int[] nums, int k) {
            Set<Integer> visited = new HashSet<>();
            Set<Integer> res = new HashSet<>();
            for (int num : nums) {
                if (visited.contains(num - k)) {
                    res.add(num - k);
                }
                if (visited.contains(num + k)) {
                    res.add(num);
                }
                visited.add(num);
            }
            return res.size();
        }
    

    排序 + 双指针

    image.png
    class Solution {
        public int findPairs(int[] nums, int k) {
            Arrays.sort(nums);
            int n = nums.length, y = 0, res = 0;
            for (int x = 0; x < n; x++) {
                if (x == 0 || nums[x] != nums[x - 1]) {
                    while (y < n && (nums[y] < nums[x] + k || y <= x)) {
                        y++;
                    }
                    if (y < n && nums[y] == nums[x] + k) {
                        res++;
                    }
                }
            }
            return res;
        }
    }
    

    来源:力扣(LeetCode)
    链接:https://leetcode.cn/problems/k-diff-pairs-in-an-array
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    相关文章

      网友评论

        本文标题:532. 数组中的 k-diff 数对

        本文链接:https://www.haomeiwen.com/subject/nhhcvrtx.html