Skip to content

Commit cfca352

Browse files
committed
feat: week02 3sum
1 parent b4d25ab commit cfca352

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

3sum/std-freejia.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public List<List<Integer>> threeSum(int[] nums) {
3+
4+
List<List<Integer>> answer = new ArrayList<>();
5+
Arrays.sort(nums);
6+
int len = nums.length;
7+
8+
for (int i = 0; i < len - 2; i++) {
9+
// 인접한 같은 수라면, 지나감
10+
if (i > 0 && nums[i] == nums[i-1]) continue;
11+
12+
int L = i + 1, H = len - 1;
13+
14+
while(L < H) {
15+
if (nums[L] + nums[H] + nums[i] > 0) {
16+
H--;
17+
} else if (nums[L] + nums[H] + nums[i] < 0) {
18+
L++;
19+
} else {
20+
answer.add(Arrays.asList(nums[i], nums[L], nums[H]));
21+
// 중복을 제거
22+
while (L < H && nums[L] == nums[L+1]) L++;
23+
while (L < H && nums[H] == nums[H-1]) H--;
24+
L++;
25+
H--;
26+
}
27+
}
28+
}
29+
return answer;
30+
}
31+
}

0 commit comments

Comments
 (0)