leetcode15 3Sum
# 15. 三数之和 (opens new window)
English Version (opens new window)
# 题目描述
给你一个包含 n
个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0
且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4] 输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = [] 输出:[]
示例 3:
输入:nums = [0] 输出:[]
提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
# 解法
“排序 + 双指针”实现。
# Python3
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
if nums is None or len(nums) < 3:
return []
nums.sort()
n = len(nums)
res = []
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
p, q = i + 1, n - 1
while p < q:
if p > i + 1 and nums[p] == nums[p - 1]:
p += 1
continue
if q < n - 1 and nums[q] == nums[q + 1]:
q -= 1
continue
if nums[i] + nums[p] + nums[q] < 0:
p += 1
elif nums[i] + nums[p] + nums[q] > 0:
q -= 1
else:
res.append([nums[i], nums[p], nums[q]])
p += 1
q -= 1
return res
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
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
# Java
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n;
if (nums == null || (n = nums.length) < 3) {
return Collections.emptyList();
}
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < n - 2; ++i) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int p = i + 1, q = n - 1;
while (p < q) {
if (p > i + 1 && nums[p] == nums[p - 1]) {
++p;
continue;
}
if (q < n - 1 && nums[q] == nums[q + 1]) {
--q;
continue;
}
if (nums[p] + nums[q] + nums[i] < 0) {
++p;
} else if (nums[p] + nums[q] + nums[i] > 0) {
--q;
} else {
res.add(Arrays.asList(nums[p], nums[q], nums[i]));
++p;
--q;
}
}
}
return res;
}
}
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
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
# JavaScript
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function (nums) {
let len = nums.length;
if (len < 3) return [];
let res = [];
nums.sort((a, b) => a - b);
for (let i = 0; i < len - 2; i++) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] === nums[i - 1]) continue;
let left = i + 1, right = len - 1;
while (left < right) {
if (nums[i] + nums[left] + nums[right] === 0) {
res.push([nums[i], nums[left], nums[right]]);
while (nums[left] === nums[left + 1]) left++;
left++;
while (nums[right] === nums[right - 1]) right--;
right--;
continue;
} else if (nums[i] + nums[left] + nums[right] > 0) {
right--;
continue;
} else {
left++;
continue;
}
}
}
return res;
};
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
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
# ...
1
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38