Leetcode 532. K diff Pairs in an Array

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

K-diff Pairs in an Array

2. Solution

  • Version 1
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
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int count = 0;
for(int i = 0; i < nums.size(); i++) {
if(i && nums[i] == nums[i - 1]) {
continue;
}
for(int j = i + 1; j < nums.size(); j++) {
if(j != i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int diff = nums[j] - nums[i];
if(diff == k) {
count++;
}
else if(diff > k) {
break;
}
}
}
return count;
}
};
  • Version 2
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
28
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
if(k < 0) {
return 0;
}
int count = 0;
unordered_map<int, int> values;
for(int n : nums) {
values[n]++;
}
if(k) {
for(auto val: values) {
if(values.count(val.first + k) > 0) {
count++;
}
}
}
else {
for(auto val: values) {
if(val.second > 1) {
count++;
}
}
}
return count;
}
};

Reference

  1. https://leetcode.com/problems/k-diff-pairs-in-an-array/description/
如果有收获,可以请我喝杯咖啡!