Skip to content

Commit 49c0cf3

Browse files
committed
3sum solution
1 parent 6be40f5 commit 49c0cf3

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

โ€Ž3sum/Yn3-3xh.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
[๋ฌธ์ œํ’€์ด]
3+
- nums ๋ฐฐ์—ด ์•ˆ์˜ 3๊ฐ€์ง€ ์ˆ˜๋ฅผ ๋”ํ–ˆ์„ ๋•Œ 0์ด์–ด์•ผ ํ•œ๋‹ค.
4+
- ๋”ํ•ด์ง„ ์ˆ˜๋“ค์˜ index๋Š” ๋ชจ๋‘ ๋‹ฌ๋ผ์•ผ ํ•œ๋‹ค.
5+
- DFS (X)
6+
StackOverflowError
7+
- ํˆฌ ํฌ์ธํ„ฐ (O)
8+
time: O(N^2), space: O(N^2)
9+
10+
[ํšŒ๊ณ ]
11+
ํ•ด์„ค์„ ๋ณด๊ณ  ์ดํ•ด๋Š” ํ–ˆ๋Š”๋ฐ ๋‹ค์‹œ ํ’€ ์ˆ˜ ์žˆ์„๊นŒ?
12+
์•„์ง ์Šคํ‚ฌ์ด ๋ถ€์กฑํ•œ ๊ฒƒ ๊ฐ™๋‹ค..
13+
14+
*/
15+
class Solution {
16+
public List<List<Integer>> threeSum(int[] nums) {
17+
Set<List<Integer>> answers = new HashSet<>();
18+
Arrays.sort(nums);
19+
20+
for (int start = 0; start < nums.length; start++) {
21+
int mid = start + 1;
22+
int end = nums.length - 1;
23+
24+
while (mid < end) {
25+
int sum = nums[start] + nums[mid] + nums[end];
26+
if (sum == 0) {
27+
List<Integer> answer = List.of(nums[start], nums[mid], nums[end]);
28+
answers.add(answer);
29+
end--;
30+
} else if (sum < 0) {
31+
mid++;
32+
} else if (sum > 0) {
33+
end--;
34+
}
35+
}
36+
}
37+
return new ArrayList<>(answers);
38+
}
39+
}

0 commit comments

Comments
ย (0)