[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:

  1. The pairs (i, j) and (j, i) count as the same pair.
  2. The length of the array won't exceed 10,000.
  3. All the integers in the given input belong to the range: [-1e7, 1e7]

思路:先把数组按小到大排序。设当前的数为 p,判断 p 后面的数减去 p是否有等于 k 的,如果有等于k的,就增加k-diff-pair然后break(因为不能重复统计),

   eg :[1,2,3,3],k=2; 到下标为 2 时,已经满足条件,就不用进行了,否则下个数还是3,这样就重复统计了。

     令p = p下一个数。如此重复,知道p到最后一个数。

     此外,我还设置了一个前驱pre等于当前数p,等p递增后,判断p是否等于pre,如果等于,则continue;(这么做也是为了不重复统计)

   eg:[1,1,2,3],k=2

class Solution {
    public int findPairs(int[] nums, int k) {
        if(nums.length==1)
            return 0;                       //如果只有一个数,返回0;
        int kDiffPair = 0;               //统计满足条件的且不重复的有多少对
        int pre = 0;        
Arrays.sort(nums);
for (int i=0;i<nums.length-1;i++){ if (i!=0&&nums[i]==pre) continue; // 如果是数组里第一个数,则前面肯定不会有重复的; for (int j = i+1;j<nums.length;j++){ if (nums[j]-nums[i]==k){ kDiffPair++; break; }
} pre
= nums[i]; //让pre等于当前的数,为了下一轮循环判断下个数是否等于pre } return kDiffPair; } }
原文地址:https://www.cnblogs.com/David-Lin/p/7722964.html