Skip to content

Commit f23ad45

Browse files
author
jinvicky
committed
3sum solution
1 parent e569877 commit f23ad45

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

3sum/jinvicky.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.List;
4+
5+
// https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/ 문제를 풀고 다시 풀었습니다.
6+
class Solution {
7+
public List<List<Integer>> threeSum(int[] nums) {
8+
List<List<Integer>> res = new ArrayList<>();
9+
Arrays.sort(nums);
10+
11+
for (int i = 0; i < nums.length; i++) {
12+
if (i > 0 && nums[i] == nums[i-1]) {
13+
continue;
14+
}
15+
16+
int j = i + 1;
17+
int k = nums.length - 1;
18+
19+
while (j < k) {
20+
int total = nums[i] + nums[j] + nums[k];
21+
22+
if (total > 0) {
23+
k--;
24+
} else if (total < 0) {
25+
j++;
26+
} else {
27+
res.add(Arrays.asList(nums[i], nums[j], nums[k]));
28+
j++;
29+
30+
while (nums[j] == nums[j-1] && j < k) {
31+
j++;
32+
}
33+
}
34+
}
35+
}
36+
return res;
37+
}
38+
}

0 commit comments

Comments
 (0)