-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathFourElementWithSum.java
72 lines (57 loc) · 1.36 KB
/
FourElementWithSum.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.*;
class FourElementWithSum {
public static void fourSum(int X, int[] arr,
Map<Integer, pair> map)
{
int[] temp = new int[arr.length];
for (int i = 0; i < temp.length; i++)
temp[i] = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
int curr_sum = arr[i] + arr[j];
if (map.containsKey(X - curr_sum)) {
pair p = map.get(X - curr_sum);
if (p.first != i && p.sec != i
&& p.first != j && p.sec != j
&& temp[p.first] == 0
&& temp[p.sec] == 0 && temp[i] == 0
&& temp[j] == 0) {
System.out.printf(
"%d,%d,%d,%d", arr[i], arr[j],
arr[p.first], arr[p.sec]);
temp[p.sec] = 1;
temp[i] = 1;
temp[j] = 1;
break;
}
}
}
}
}
public static Map<Integer, pair> twoSum(int[] nums)
{
Map<Integer, pair> map = new HashMap<>();
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
map.put(nums[i] + nums[j], new pair(i, j));
}
}
return map;
}
public static class pair {
int first, sec;
public pair(int first, int sec)
{
this.first = first;
this.sec = sec;
}
}
public static void main(String args[])
{
int[] arr = { 10, 20, 30, 40, 1, 2 };
int n = arr.length;
int X = 91;
Map<Integer, pair> map = twoSum(arr);
fourSum(X, arr, map);
}
}