剑指 Offer II 007. 数组中和为 0 的三个数
原文链接:https://blog.csdn.net/qq_39355828/article/details/120423612 (opens new window) 剑指 Offer II 007. 数组中和为 0 的三个数
给定一个包含 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]
输出:[]
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//List<List<Integer>> ans=new LinkedList<>();
Set<List<Integer>>res=new HashSet<>();
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++)
{
int left=i+1,right=nums.length-1;
while(left<right)
{
if(nums[i]+nums[nums.length-1]+nums[nums.length-2]<0) {
break;
}
if(nums[i]+nums[left]+nums[right]<0) {
left++;
continue;
}
if(nums[i]+nums[left]+nums[right]>0) {
right--;
continue;
}
if(nums[i]+nums[left]+nums[right]==0) {
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
left++;
}
}
}
return new ArrayList<>(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
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
编辑 (opens new window)
上次更新: 2026/08/11, 13:36:18