Skip to content

Commit a9bbcff

Browse files
committed
added kdiffpairs
1 parent 38d2dc9 commit a9bbcff

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

october/kdiffpairs.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
3+
Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.
4+
5+
A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:
6+
7+
0 <= i, j < nums.length
8+
i != j
9+
|nums[i] - nums[j]| == k
10+
Notice that |val| denotes the absolute value of val.
11+
12+
13+
14+
Example 1:
15+
16+
Input: nums = [3,1,4,1,5], k = 2
17+
Output: 2
18+
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
19+
Although we have two 1s in the input, we should only return the number of unique pairs.
20+
21+
22+
Input: nums = [1,3,1,5,4], k = 0
23+
Output: 1
24+
Explanation: There is one 0-diff pair in the array, (1, 1).
25+
*/
26+
27+
//solution
28+
29+
30+
class Solution {
31+
public:
32+
int findPairs(vector<int>& nums, int k) {
33+
unordered_map<int,int> hashmap;
34+
for(int i:nums){
35+
hashmap[i]++;
36+
}
37+
38+
int res=0;
39+
for(auto p:hashmap){
40+
int x = p.first;
41+
42+
if(hashmap.find(x+k)==hashmap.end()){
43+
continue;
44+
}
45+
//man this is some crazy code
46+
// if k=0 then we need to consider only those nums that have repeated more than once
47+
// if k!=0 then for every x we need to check if x+k is in map
48+
res+=(k==0)? (hashmap[x+k]>=2) : hashmap[x+k]>=1;
49+
}
50+
51+
52+
return res;
53+
54+
}
55+
};

0 commit comments

Comments
 (0)