Skip to content

Commit 02fdf7a

Browse files
committed
3Sum
1 parent a0c0755 commit 02fdf7a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

3sum/TonyKim9401.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// TC: O(n^2)
2+
// SC: O(n)
3+
public class Solution {
4+
public List<List<Integer>> threeSum(int[] nums) {
5+
6+
Arrays.sort(nums);
7+
8+
List<List<Integer>> output = new ArrayList<>();
9+
Map<Integer, Integer> map = new HashMap<>();
10+
11+
for (int i = 0; i < nums.length; ++i) map.put(nums[i], i);
12+
13+
for (int i = 0; i < nums.length - 2; ++i) {
14+
if (nums[i] > 0) break;
15+
16+
for (int j = i + 1; j < nums.length - 1; ++j) {
17+
int cValue = -1 * (nums[i] + nums[j]);
18+
19+
if (map.containsKey(cValue) && map.get(cValue) > j) {
20+
output.add(List.of(nums[i], nums[j], cValue));
21+
}
22+
j = map.get(nums[j]);
23+
}
24+
25+
i = map.get(nums[i]);
26+
}
27+
28+
return output;
29+
}
30+
}

0 commit comments

Comments
 (0)