Skip to content

Commit 631d069

Browse files
committed
15. 三数之和
1 parent 2f74607 commit 631d069

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package com.geekidentity.leetcode.n0015;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
/**
8+
* 15. 三数之和
9+
* https://leetcode-cn.com/problems/3sum/
10+
* 1. 暴击
11+
* 2. 双指针,左右下标向中间推进
12+
*/
13+
public class ThreeSum {
14+
public List<List<Integer>> threeSum1(int[] nums) {
15+
List<List<Integer>> result = new ArrayList<>();
16+
for (int i = 0; i < nums.length - 2; i++) {
17+
for (int j = i + 1; j < nums.length - 1; j++) {
18+
for (int k = j + 1; k < nums.length; k++) {
19+
if (nums[i] + nums[j] + nums[k] == 0) {
20+
result.add(Arrays.asList(nums[i], nums[j], nums[k]));
21+
}
22+
}
23+
}
24+
}
25+
return result;
26+
}
27+
28+
public List<List<Integer>> threeSum2(int[] nums) {
29+
List<List<Integer>> result = new ArrayList<>();
30+
Arrays.sort(nums);
31+
for (int i = 0; i < nums.length - 2; i++) {
32+
if (i > 0 && nums[i] == nums[i - 1]) continue;
33+
for (int j = i + 1, k = nums.length - 1; j < k;) {
34+
int target = -nums[i];
35+
int sum = nums[j] + nums[k];
36+
if (sum == target) {
37+
result.add(Arrays.asList(nums[i], nums[j], nums[k]));
38+
j++;
39+
k--;
40+
while (j < k && nums[j] == nums[j - 1]) {
41+
j++;
42+
}
43+
while (j < k && nums[k] == nums[k + 1]) {
44+
k--;
45+
}
46+
} else if (sum < target) {
47+
j++;
48+
} else {
49+
k--;
50+
}
51+
}
52+
}
53+
return result;
54+
}
55+
}

0 commit comments

Comments
 (0)