Skip to content

Commit 60381b4

Browse files
author
Wang Dongxu
committed
docs: add comment on 3Sum problem
1 parent 6237b6e commit 60381b4

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

src/com/blankj/medium/_015/Solution.java

+8
Original file line numberDiff line numberDiff line change
@@ -10,27 +10,35 @@
1010
* blog : http://blankj.com
1111
* time : 2017/10/14
1212
* desc :
13+
* 题意是让你从数组中找出所有三个和为 0 的元素构成的非重复序列,这样的话我们可以把数组先做下排序,
14+
* 然后遍历这个排序数组,用两个指针分别指向当前元素的下一个和数组尾部,判断三者的和与 0 的大小来移动两个指针,
15+
* 其中细节操作就是优化和去重。
1316
* </pre>
1417
*/
1518
public class Solution {
1619
public List<List<Integer>> threeSum(int[] nums) {
1720
List<List<Integer>> list = new ArrayList<>();
1821
int len = nums.length;
1922
if (len < 3) return list;
23+
// 先排序
2024
Arrays.sort(nums);
2125
int max = nums[len - 1];
26+
// 最大值小于0, 那么不存在sum == 0 的解
2227
if (max < 0) return list;
2328
for (int i = 0; i < len - 2; ) {
29+
// 最小值小于0, 那么不存在sum == 0 的解
2430
if (nums[i] > 0) break;
2531
if (nums[i] + 2 * max < 0) {
2632
while (nums[i] == nums[++i] && i < len - 2) ;
2733
continue;
2834
}
35+
// 对于任意一个nums[i],在数组中的其他数中解2sum问题,目标为target-sums[i]
2936
int left = i + 1, right = len - 1;
3037
while (left < right) {
3138
int sum = nums[i] + nums[left] + nums[right];
3239
if (sum == 0) {
3340
list.add(Arrays.asList(nums[i], nums[left], nums[right]));
41+
// 去重
3442
while (nums[left] == nums[++left] && left < right) ;
3543
while (nums[right] == nums[--right] && left < right) ;
3644
} else if (sum < 0) ++left;

0 commit comments

Comments
 (0)