1. 程式人生 > >Leetcode532. 找出陣列中絕對值為k的數值對的數目

Leetcode532. 找出陣列中絕對值為k的數值對的數目

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

Example1:
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.

Example2:
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).

Example3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).

解題分析

題目乍一看,給我的第一思路就是要消除陣列中重複的元素;因為題目明確說了,相同的元素只算一次。

接下來我們來考慮怎樣統計陣列中絕對值為k的數值對的數目。我們可以這樣想,用另外一個數組來儲存每個元素對應的數值對的值。而我們知道絕對值為k的數字有兩個,即k和-k。因此,在前面消除陣列重複元素的時候,對陣列從小到大進行排序,這樣可以只考慮一種情況而減少重複工作。
在遍歷陣列元素的時候,我們先判斷在另一個數組中有沒有該陣列元素,如果有,說明就找到了一個數值對;然後再把該元素對應的數值對的值(即該元素的值+k)存進陣列中。這樣當陣列遍歷完之後,數目的計算就完成了。

但是這裡還有一個細節問題容易忽略,就是k=0的情況。前面我們消除了陣列的重複元素,因此此時陣列中沒有任何一個重複元素,如果我們按照上面的做法,最後的結果就始終為0。所以,在消除陣列重複元素之前,我們需要用unordered_map雜湊表來統計每個元素出現的次數,如果次數大於1,數值對的數目就加1,這樣所有的問題就解決了。

原始碼

class Solution {
public:
    int findPairs(vector<int>& nums, int k) {
        int pair = 0, size = nums.size(), i;
        unordered_map<int, int> map;
        for (i = 0; i < size; i++) {
            map[nums[i]]++;
        }
        sort(nums.begin(), nums.end());
        vector<int>::iterator end_unique = unique(nums.begin(), nums.end());
        nums.erase(end_unique, nums.end());
        if (k == 0) {
            for (i = 0; i < nums.size(); i++) {
                if (map[nums[i]] > 1) {
                    pair++;
                }
            }
        }
        else if (k > 0) {
            vector<int> add;
            for (i = 0; i < nums.size(); i++) {
                vector<int>::iterator it_add = find(add.begin(), add.end(), nums[i]);
                if (it_add != add.end()) {
                    pair++;
                }
                add.push_back(nums[i] + k);
            }
        }
        return pair;
    }
};

這只是我對這道題的一些想法,有問題還請在評論區討論留言~