-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoPairsWithSameSum.java
More file actions
45 lines (40 loc) · 1.09 KB
/
TwoPairsWithSameSum.java
File metadata and controls
45 lines (40 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
45
package datastructure.hashtable;
import java.util.HashMap;
/**
* The type Two pairs with same sum.
*/
public class TwoPairsWithSameSum {
/**
* Find pair string.
*
* @param arr the arr
* @return the string
*/
public static String findPair(int[] arr) {
HashMap<Integer, int[]> map = new HashMap<>();
String result = "";
int l = arr.length;
for (int i = 0; i < l; i++) {
for (int j = i + 1; j < l; j++) {
int sum = arr[i] + arr[j];
if (!map.containsKey(sum))
map.put(sum, new int[]{arr[i], arr[j]});
else {
int prevPair[] = map.get(sum);
result += "{" + prevPair[0] + "," + prevPair[1] + "}{" + arr[i] + "," + arr[j] + "}";
return result;
}
}
}
return result;
}
/**
* Main.
*
* @param args the args
*/
public static void main(String args[]) {
int[] arr = {3, 4, 7, 1, 12, 9};
System.out.println(findPair(arr));
}
}