Skip to content

Commit 158003b

Browse files
committed
3sum solution
1 parent c0070c9 commit 158003b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

3sum/hyunolike.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
public List<List<Integer>> threeSum(int[] nums) {
3+
List<List<Integer>> result = new ArrayList<>();
4+
5+
int n = nums.length;
6+
if (n < 3) return result;
7+
8+
Arrays.sort(nums);
9+
10+
for(int i = 0; i < n - 2; i++) {
11+
if(i > 0 && nums[i] == nums[i-1]) continue;
12+
13+
int left = i + 1;
14+
int right = n - 1;
15+
16+
while(left < right) {
17+
int sum = nums[i] + nums[left] + nums[right];
18+
19+
if(sum < 0){
20+
left++;
21+
}
22+
else if(sum > 0) {
23+
right --;
24+
}
25+
else {
26+
// sum == 0 → 조합 하나 찾음
27+
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
28+
29+
// left, right 중복값 스킵
30+
int leftVal = nums[left];
31+
int rightVal = nums[right];
32+
33+
while (left < right && nums[left] == leftVal) left++;
34+
while (left < right && nums[right] == rightVal) right--;
35+
}
36+
}
37+
}
38+
39+
return result;
40+
}
41+
}

0 commit comments

Comments
 (0)