leetcode题解-532. K-diff Pairs in an Array

题目:

Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
Note:
The pairs (i, j) and (j, i) count as the same pair.
The length of the array won't exceed 10,000.
All the integers in the given input belong to the range: [-1e7, 1e7].

本题是寻找数组中差为k的数对的个数。首先我们想到的一种方式是将数组进行排序,然后嵌套循环遍历数组,这种方法有两个点需要注意,一是跳过重复的数字,二是对每个数字一旦找到则停止内循环,这样可以节省运行时间。代码入下:

    public static int findPairs(int[] nums, int k) {
        Arrays.sort(nums);
        int res = 0;
        for(int i=0; i1; i++){
            for(int j=i+1; jif(nums[j] - nums[i] == k) {
                    res++;
                    break;
                }
            while(i1 && nums[i] == nums[i+1])
                i++;
        }
        return res;
    }

第二种方法是使用HashMap来保存数字信息,这样就省去了一次遍历的时间,代码效率提升很多。代码入下:

    public int findPairs(int[] nums, int k) {
        if (k < 0)   return 0;
        HashMap freqmap = new HashMap();
        int count = 0;
        for(int num:nums){
            int f = (int)freqmap.getOrDefault(num, 0)+1;
            freqmap.put(num, f);
        }
        for (Integer key : freqmap.keySet()) {
            int a = (int)key;
            int b = a + k;
            if(!freqmap.containsKey(b)) continue;
            int bfreq = freqmap.get(b);
            int minfreq = a==b ? 2:1;
            if(bfreq>=minfreq ){
                count++;
                freqmap.put(a,1);
            }
        }
        return count;
    }

第三种方法是效率最高的方法,击败了98%的用户。这种方法的主要思路就是先对数组排序,然后使用滑动窗口遍历数组,因为数组排序之后差是可以连续移动两个指针得到的==这种方法同样要对相同的数字进行排除。代码入下:

    public  int findPairs1(int[] nums, int k) {
        if(k<0 || nums.length<=1){
            return 0;
        }

        Arrays.sort(nums);
        int count = 0;
        int left = 0;
        int right = 1;

        while(rightint firNum = nums[left];
            int secNum = nums[right];
            if(secNum-firNumright++;
            else if(secNum - firNum>k)
                left++;
            else{
                count++;
                while(leftleft]==firNum){
                    left++;
                }
                while(rightright]==secNum){
                    right++;
                }

            }
            if(right==left){
                right++;
            }
        }
        return count;
    }

你可能感兴趣的:(leetcode刷题)