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].

解題思路

我在解這道題時,主要踩進了三個坑:

  1. 結果中的 k-diff pairs 不允許重複。比如 example1 的數組中,含有兩個 1 ,這樣,在遍歷所有的結果後會得到 (1, 3), (1, 3) and (3, 5) ,但由於不允許重複,所以只能有一個 (1, 3)
  2. k == 0 時又必須要考慮重複,因爲只有重複的數字才能組成滿足條件的 k-diff pair
  3. k < 0 時,無解,返回 0

針對以上三個坑,最後得出的解題思路如下:因爲 (i, j)(j, i) 視爲相同,因此可以創建一個集合,當掃描得到 (i, j) 時,把 ij 中較大的那一個數存入集合中,代表 (i, j)(j, i) 兩個 k-diff pairs 都已經存進集合中了 ,這樣,當掃描得到 (j, i) 時,由於ij 中較大的那一個數已經在集合中,則不再需要添加了,這樣就可以解決上面的坑了,最後返回集合的元素個數即可。需要創建兩個集合,其中一個用於保存結果,另一個用於實現哈希查找。

Java代碼實現

class Solution {
    public int findPairs(int[] nums, int k) {
        Set<Integer> rstPairs = new HashSet<>();
        Set<Integer> hash = new HashSet<>();

        if (k < 0) { return 0; }

        for (int num : nums) {
            if (hash.contains(num - k)) {
                if (!rstPairs.contains(num))
                    rstPairs.add(num);
            }
            if (hash.contains(num + k)) {
                if (!rstPairs.contains(num + k))
                    rstPairs.add(num + k);
            }

            if (!hash.contains(num))
                hash.add(num);
        }

        return rstPairs.size();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章