forked from coder2hacker/Explore-open-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dvd1234.java
39 lines (35 loc) · 955 Bytes
/
Dvd1234.java
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
package java;
import java.util.*;
/*
Given an array of N integers, and a number sum, the task is to find the number of pairs of integers
in the array whose sum is equal to sum.
*/
class PairWithGivenSum {
static int getPairsCount(int arr[], int n, int k)
{
HashMap<Integer, Integer> m = new HashMap<>();
int count = 0;
for (int i = 0; i < n; i++) {
if (m.containsKey(k - arr[i])) {
count += m.get(k - arr[i]);
}
if (m.containsKey(arr[i])) {
m.put(arr[i], m.get(arr[i]) + 1);
}
else {
m.put(arr[i], 1);
}
}
return count;
}
public static void main(String[] args)
{
int arr[] = { 1, 5, 7, -1, 5 };
int sum = 6;
System.out.print("Count of pairs is " + getPairsCount(arr, arr.length, sum));
}
}
/*
Time Complexity: O(n),
Auxiliary Space: O(n),
*/