0%

力扣每日一题2021/9/5

题目:15. 三数之和

给你一个包含 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
  • -10^5 <= nums[i] <= 10^5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

排序 + 双指针

官方解题代码

排序 + 双指针

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
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<>();
for (int first = 0; first < nums.length; first++){
if (first > 0 && nums[first] == nums[first - 1]){
continue;
}
int third = nums.length - 1;
for (int second = first + 1; second < nums.length; second++){
if (second > first + 1 && nums[second] == nums[second - 1]){
continue;
}
while (second < third && nums[first] + nums[second] + nums[third] > 0){
third--;
}
if (second == third){
break;
}
if (nums[first] + nums[second] + nums[third] == 0){
ans.add(Arrays.asList(nums[first], nums[second], nums[third]));
}
}
}
return ans;
}
}