forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbky373.java
More file actions
37 lines (36 loc) · 984 Bytes
/
bky373.java
File metadata and controls
37 lines (36 loc) · 984 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
31
32
33
34
35
36
37
/**
* time: O(n^2)
* space: O(n)
*
* - time: becasue of two nested loop and inner loop having a linear time complexity.
* - space: because of a HashSet to store the triplets.
*/
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
int i = 0, j, k;
int ni = 0, nj, nk;
Set<List<Integer>> res = new HashSet<>();
while (i < nums.length && ni <= 0) {
ni = nums[i];
j = i + 1;
k = nums.length - 1;
while (j < k) {
nj = nums[j];
nk = nums[k];
int sum = ni + nj + nk;
if (sum < 0) {
j++;
} else if (sum > 0) {
k--;
} else {
res.add(List.of(ni, nj, nk));
j++;
}
}
i++;
}
return res.stream()
.toList();
}
}