leetcode (K-diff Pairs in an Array)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/84558397

Title:K-diff Pairs in an Array    532

Difficulty:Easy

原题leetcode地址:https://leetcode.com/problems/k-diff-pairs-in-an-array/

1. 首先排序,然后嵌套循环遍历数组,注意(a.如果找到一对,就跳出本次循环(内循环),b.跳过重复的数)

时间复杂度:O(n^2),两层循环。

空间复杂度:O(1),没有申请额外空间。

    /**
     * 1. 排序
     * 2. 嵌套循环遍历数组:
     *      如果找到一对,就跳出本次循环(内循环)
     *      跳过重复的数
     * @param nums
     * @param k
     * @return
     */
    public static int findPairs(int[] nums, int k) {

        if (nums == null || nums.length <= 0 || k < 0) {
            return 0;
        }

        Arrays.sort(nums);
        int count = 0;

        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] - nums[i] == k) {
                    count++;
                    break;
                }
            }
            while (i < nums.length - 1 && nums[i] == nums[i + 1]) {
                i++;
            }
        }

        return count;

    }

2. 滑动窗口

时间复杂度:O(n^2),两层循环,最长是n^2。

空间复杂度:O(1),没有申请额外空间。

    /**
     * 滑动窗口
     * 1. 排序
     * 2. 双指针 (跳过重复的数)
     * @param nums
     * @param k
     * @return
     */
    public static int findPairs1(int[] nums, int k) {

        if (nums == null || nums.length <= 0 || k < 0) {
            return 0;
        }

        Arrays.sort(nums);

        int count = 0;
        int firstIndex = 0;
        int secondIndex = 1;

        while (secondIndex < nums.length) {
            int firstNum = nums[firstIndex];
            int secondNum = nums[secondIndex];
            if (secondNum - firstNum < k) {
                secondIndex++;
            }
            else if (secondNum - firstNum > k) {
                firstIndex++;
            }
            else {
                count++;
                // 跳过重复的数
                while (firstIndex < nums.length && firstNum == nums[firstIndex]) {
                    firstIndex++;
                }
                // 跳过重复的数
                while (secondIndex < nums.length && secondNum == nums[secondIndex]) {
                    secondIndex++;
                }
            }
            if (firstIndex == secondIndex) {
                secondIndex++;
            }
        }

        return count;

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/84558397