-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathKDiffPairsInAnArray.cs
More file actions
46 lines (42 loc) · 1.09 KB
/
Copy pathKDiffPairsInAnArray.cs
File metadata and controls
46 lines (42 loc) · 1.09 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//Time Complexity : O(n)
//Space Complexity : O(n)
//Approach
// Maintain Dictionary with keys and elements from the array , values as frequency
// Iterate over keys and check sum = Key + K ,if dictionary contains that sum then count it as one pair
// If K is 0 then make sure frequency is greater than 1 then count.
public class Solution
{
public int FindPairs(int[] nums, int k)
{
int count = 0;
Dictionary<int, int> pair = new();
for (int i = 0; i < nums.Length; i++)
{
if (!pair.ContainsKey(nums[i]))
{
pair.TryAdd(nums[i], 1);
}
else
{
pair[nums[i]]++;
}
}
foreach (var key in pair.Keys)
{
int sum = key + k;
if (k == 0)
{
int val = pair[key];
if (val > 1)
{
count++;
}
}
else if (pair.ContainsKey(sum))
{
count++;
}
}
return count;
}
}