forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTonyKim9401.java
More file actions
30 lines (22 loc) · 800 Bytes
/
TonyKim9401.java
File metadata and controls
30 lines (22 loc) · 800 Bytes
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
// TC: O(n^2)
// SC: O(n)
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> output = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; ++i) map.put(nums[i], i);
for (int i = 0; i < nums.length - 2; ++i) {
if (nums[i] > 0) break;
for (int j = i + 1; j < nums.length - 1; ++j) {
int cValue = -1 * (nums[i] + nums[j]);
if (map.containsKey(cValue) && map.get(cValue) > j) {
output.add(List.of(nums[i], nums[j], cValue));
}
j = map.get(nums[j]);
}
i = map.get(nums[i]);
}
return output;
}
}