LeetCode15-三数之和

题目链接

英文链接:https://leetcode.com/problems/3sum/

中文链接:https://leetcode-cn.com/problems/3sum/

题目详述

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

1
2
3
4
5
6
7
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

题目详解

“数组 + 有序”的问题一般可以联想到二分查找,也有很多可以用双指针来解决。

  • 首先把数组从小到大进行排序。
  • 遍历过程中固定一个元素。
  • 再运用双指针的思想,一个从左往右扫描,一个从右往左扫描。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class LeetCode_00015 {

public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new LinkedList<>();
// 首先从小到大排序
Arrays.sort(nums);
int n = nums.length;
for (int i = 0; i < n; ++i) {
// 第一个数大于 0,后面的两个数都大于或等于第一个数,从此三数之和肯定大于 0,直接退出
if (nums[i] > 0) {
break;
}
// 让第一个数不同,避免重复
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int l = i + 1;
int r = n - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
if (sum > 0) { // 因为数组有序,说明右侧的数过大,所以下标左移
--r;
} else if (sum < 0) { // 因为数组有序,说明左侧的数过小,所以下标右移
++l;
} else {
res.add(Arrays.asList(nums[i], nums[l++], nums[r--]));
// 两侧的下标向中间移动,直到不与之前取出的数相同,避免出现重复的三元组
while (l < r && nums[l] == nums[l - 1]) {
++l;
}
while (l < r && nums[r] == nums[r + 1]) {
--r;
}
}
}
}
return res;
}
}