From b7249672198739862806804c117f30b2443fdfe1 Mon Sep 17 00:00:00 2001 From: Rachit Jain <32428330+rachitiitr@users.noreply.github.com> Date: Sun, 4 Oct 2020 13:33:53 +0530 Subject: [PATCH] Day3 Coding Interview || k-diff-pairs-in-an-array Easy --- LeetCode/532.k-diff-pairs-in-an-array.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LeetCode/532.k-diff-pairs-in-an-array.cpp diff --git a/LeetCode/532.k-diff-pairs-in-an-array.cpp b/LeetCode/532.k-diff-pairs-in-an-array.cpp new file mode 100644 index 0000000..eda9324 --- /dev/null +++ b/LeetCode/532.k-diff-pairs-in-an-array.cpp @@ -0,0 +1,21 @@ +using hashmap = unordered_map; + +class Solution { +public: + int findPairs(vector& nums, int k) { + hashmap cnt; + for(int x: nums) cnt[x]++; + + int ans = 0; + for(auto p: cnt) { // iterating on unique numbers of the array + int x = p.first; + // check x+k exists in the array + if(cnt.find(x+k) == cnt.end()) { + continue; + } + ans += (k==0) ? cnt[x+k] >= 2 : cnt[x+k] >= 1; + } + + return ans; + } +};