forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYn3-3xh.java
More file actions
39 lines (35 loc) Β· 1.1 KB
/
Yn3-3xh.java
File metadata and controls
39 lines (35 loc) Β· 1.1 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
/*
[λ¬Έμ νμ΄]
- nums λ°°μ΄ μμ 3κ°μ§ μλ₯Ό λνμ λ 0μ΄μ΄μΌ νλ€.
- λν΄μ§ μλ€μ indexλ λͺ¨λ λ¬λΌμΌ νλ€.
- DFS (X)
StackOverflowError
- ν¬ ν¬μΈν° (O)
time: O(N^2), space: O(N^2)
[νκ³ ]
ν΄μ€μ λ³΄κ³ μ΄ν΄λ νλλ° λ€μ ν μ μμκΉ?
μμ§ μ€ν¬μ΄ λΆμ‘±ν κ² κ°λ€..
*/
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> answers = new HashSet<>();
Arrays.sort(nums);
for (int start = 0; start < nums.length; start++) {
int mid = start + 1;
int end = nums.length - 1;
while (mid < end) {
int sum = nums[start] + nums[mid] + nums[end];
if (sum == 0) {
List<Integer> answer = List.of(nums[start], nums[mid], nums[end]);
answers.add(answer);
end--;
} else if (sum < 0) {
mid++;
} else if (sum > 0) {
end--;
}
}
}
return new ArrayList<>(answers);
}
}