forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchjung99.java
More file actions
48 lines (42 loc) · 1.3 KB
/
chjung99.java
File metadata and controls
48 lines (42 loc) · 1.3 KB
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
// two pointer
// time: O(N^2)
// space: O(N)
class Solution {
Set<List<Integer>> set = new HashSet<>();
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++){
twoSum(nums, i);
}
return new ArrayList<>(set);
}
public void twoSum(int[] nums, int targetIdx){
int left = 0;
int right = nums.length - 1;
while (left < right) {
if (left == targetIdx){
left ++;
continue;
}
if (right == targetIdx){
right--;
continue;
}
if (nums[left] + nums[right] == -nums[targetIdx]) {
if (nums[left] > nums[targetIdx]){
set.add(List.of(nums[targetIdx], nums[left], nums[right]));
}
else if (nums[targetIdx] > nums[right]){
set.add(List.of(nums[left],nums[right],nums[targetIdx]));
} else{
set.add(List.of(nums[left], nums[targetIdx], nums[right]));
}
left++;
} else if (nums[left] + nums[right] < -nums[targetIdx]){
left ++;
} else {
right --;
}
}
}
}