[LeetCode] 15. 三数之和
题目链接:https://leetcode-cn.com/problems/3sum/
题目描述:
给定一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路:
固定一个值,找另外二个值它们和等于 0
,
如何找另外两个值,用的是双指针!
关注我的知乎专栏,了解更多解题技巧.
代码:
python
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
n = len(nums)
res = []
#print(nums)
for i in range(n):
if i > 0 and nums[i] == nums[i-1]:
continue
left = i + 1
right = n - 1
while left < right:
cur_sum = nums[i] + nums[left] + nums[right]
if cur_sum == 0:
tmp = [nums[i],nums[left],nums[right]]
res.append(tmp)
while left < right and nums[left] == nums[left+1]:
left += 1
while left < right and nums[right] == nums[right-1]:
right -= 1
left += 1
right -= 1
elif cur_sum > 0:
right -= 1
else:
left += 1
return res
java
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
List<List<Integer>> res = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = n - 1;
while (left < right) {
int tmp = nums[i] + nums[left] + nums[right];
if (tmp == 0) {
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) left += 1;
while (left < right && nums[right] == nums[right - 1]) right -= 1;
left += 1;
right -= 1;
} else if (tmp > 0) right -= 1;
else left += 1;
}
}
return res;
}
}