Skip to content

Commit 7b32f39

Browse files
committed
3sum solution
1 parent 0315273 commit 7b32f39

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

3sum/ohgyulim.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.util.*;
2+
3+
class Solution {
4+
/* 시간 복잡도: O(N^2)
5+
* - for 루프: O(N)
6+
* - while 루프: O(N) -> N^2
7+
* 공간 복잡도: O(K), answer의 K = List<Integer> 개수
8+
*/
9+
public List<List<Integer>> threeSum(int[] nums) {
10+
Arrays.sort(nums);
11+
12+
List<List<Integer>> answer = new ArrayList<>();
13+
for (int i = 0; i < nums.length - 2; i++) {
14+
if (i > 0 && nums[i] == nums[i - 1]) continue;
15+
16+
int left = i + 1;
17+
int right = nums.length - 1;
18+
19+
while (left < right) {
20+
int sum = nums[i] + nums[left] + nums[right];
21+
if (sum == 0) {
22+
answer.add(List.of(nums[i], nums[left], nums[right]));
23+
while (left < right && nums[left] == nums[left + 1]) left += 1;
24+
while (left < right && nums[right] == nums[right - 1]) right -= 1;
25+
left += 1;
26+
right -= 1;
27+
} else if (sum < 0) left += 1;
28+
else right -= 1;
29+
}
30+
}
31+
32+
return answer;
33+
}
34+
}

0 commit comments

Comments
 (0)