0%

k-diff-pairs-in-an-array

K-diff Pairs in an Array – LeetCode 532

Problem

Description

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.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
if(k < 0) return 0;
sort(nums.begin(), nums.end());
int cnt = 0;
if(k){
for(auto p = nums.cbegin(); p != nums.cend(); ++p){
while((p + 1) != nums.cend() && *(p + 1) == *p) ++p;
cnt += binary_search(p+1, nums.cend(), *p + k);
}
} else {
bool flag = false;
for(auto p = nums.cbegin(); p != nums.cend(); ++p){
while((p + 1) != nums.cend() && *(p + 1) == *p){
++p;
flag = true;
}
if(flag){
++cnt;
flag = false;
}
}
}
return cnt;
}
};

思路

要求特定差的数对,为了节省空间优先排序。然后保证单项次序下从前向后查找理想值。时间复杂度$O(nlog(n))$,空间复杂度$O(1)$。
耗时$16$ ms,排名$1.98\%$

Better

思路

通过存储对应值的出现次数,借助hash表做到对于期望值接近于常数时间的查询。典型的用空间换时间,具体耗时取决于数据结构的实现。时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$20$ ms,排名$6.87\%$

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
if(k < 0) return 0;
int res = 0, n = nums.size();
unordered_map<int, int> m;
for (int num : nums) ++m[num];
if(k){
for (auto a : m)
if (m.count(a.first + k)) ++res;
} else {
for (auto a : m)
if (a.second > 1) ++res;
}
return res;
}
};