Skip to content

Commit bd33b29

Browse files
authored
K-diff Pairs in an Array (C++) (#62)
* K-diff pairs in an array (C++) added * K-diff pairs in an array (C++) Added
1 parent cb60463 commit bd33b29

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

C++/k-diff-pairs-in-an-array.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// A simple cpp solution using maps and set
2+
3+
class Solution {
4+
public:
5+
int findPairs(vector<int>& nums, int k) {
6+
7+
map<int,int> m;
8+
set<pair<int,int>> sp;
9+
10+
// create a map storing all the frequencies
11+
for(int i:nums) m[i]++;
12+
13+
int ans=0;
14+
for(auto i:m){
15+
16+
// if k = 0, add one entry to the set if freq > 1
17+
if(k==0 && m[i.first]>1){
18+
sp.insert({i.first,i.first});
19+
}
20+
else if(k!=0 && m.find(i.first+k)!=m.end()){
21+
sp.insert({i.first,i.second});
22+
}
23+
}
24+
25+
// answer is the number of elements in the set
26+
return sp.size();
27+
}
28+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
103103
| 495 | [Teemo Attacking](https://leetcode.com/problems/teemo-attacking) | [C++](./C++/teemo-attacking.cpp) | _O(n)_ | _O(1)_ | Medium| Array | |
104104
| 15 | [3 Sum](https://leetcode.com/problems/3sum/) | [Python](./Python/ThreeNumbersSum.py) | O( nLog(n) ) | O(1) | Medium | Array |
105105
| 1200 | [Minimum Absolute Difference](https://leetcode.com/problems/minimum-absolute-difference/) | [Python](./python/SmallestDifference.py) | O(n) | O(1) | Easy | Array |
106+
| 532 | [K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array/) | [C++](./C++/k-diff-pairs-in-an-array.cpp) | O(n) | O(n) | Medium | Array |
106107

107108

108109
<br/>

0 commit comments

Comments
 (0)