-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreeSum.java
111 lines (96 loc) · 2.73 KB
/
ThreeSum.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import java.util.HashMap;
import java.util.HashSet;
// Amazon question
// Given an array S of n integers, are there elements a, b, c in S
// such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
// Note: The solution set must not contain duplicate triplets.
// For example, given array S = [-1, 0, 1, 2, -1, -4],
// A solution set is:
// [
// [-1, 0, 1],
// [-1, -1, 2]
// ]
import java.util.LinkedList;
import java.util.List;
public class ThreeSum {
public List<List<Integer>> threeSum(int[] nums) {
HashMap<Integer, Integer> positive = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> negative = new HashMap<Integer, Integer>();
int numZeros = 0;
// Place numbers into maps
for (int x : nums) {
if (x != 0) {
HashMap<Integer, Integer> set;
if (x >= 0) {
set = positive;
} else {
set = negative;
}
Integer y = set.get(x);
// System.out.print("key: " + x);
if (y == null) {
set.put(x, 1);
} else {
set.put(x, ++y);
}
// System.out.println(" updated value: " + set.get(x));
} else {
numZeros++;
}
}
// Calculate sums
List<List<Integer>> sums = new LinkedList<List<Integer>>();
HashSet<Integer> lookedAt = new HashSet<Integer>();
for (int y : nums) {
List<Integer> sumZero = new LinkedList<Integer>();
HashMap<Integer, Integer> set;
if (lookedAt.contains(y)) {
continue;
} else {
lookedAt.add(y);
}
if (y <= 0) {
set = positive;
} else {
set = negative;
}
// check with opposite sign numbers
// Iterate over unique values in opposite sign set
if (y != 0) {
for (int z : set.keySet()) {
int numNeeded = -(y + z);
if (numNeeded == z) {
// Check if z appears multiple times
int numOccur = set.get(z);
System.out.println(numNeeded + " " + y + " " + z);
System.out.println(numOccur);
if (numOccur > 1) {
sumZero.add(y);
sumZero.add(z);
sumZero.add(z);
}
} else {
if (set.containsKey(numNeeded)) {
sumZero.add(y);
sumZero.add(z);
sumZero.add(numNeeded);
}
}
}
// check with zero
if (y < 0 && numZeros > 0) {
int needed = -y;
if (set != null && set.containsKey(-y)) {
sumZero.add(y);
sumZero.add(-y);
sumZero.add(0);
}
}
}
if (sumZero.size() != 0) {
sums.add(sumZero);
}
}
return sums;
}
}