1. 程式人生 > >[Leetcode]532. K-diff Pairs in an Array

[Leetcode]532. K-diff Pairs in an Array

elong lan ray 有一個 wiki xpl exce define code

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

[Leetcode]532. K-diff Pairs in an Array