https://leetcode-cn.com/problems/3sum/submissions/
难度中等3668
给你一个包含 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
通过次数617,705提交次数1,858,277
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
//先排序(避免重复元素)
Arrays.sort(nums);
/*
二重循环:
1.一层循环,确定target
2.二层循环,找到两个数 == target
*/
for(int a=0;a<nums.length;a++)
{
if(a>0 && nums[a] == nums[a-1]) continue;
int target = -nums[a];
for(int b = a+1,c=nums.length-1;b<c;b++)
{
if(b>a+1 && nums[b] == nums[b-1]) continue;
while(b<c && nums[b]+nums[c]>target) c--;
if(b!=c && (nums[b]+nums[c])==target)
{
List<Integer> l = new ArrayList<Integer>();
l.add(nums[a]);
l.add(nums[b]);
l.add(nums[c]);
ans.add(l);
}
}
}
return ans;
}
}

该博客介绍了一个中等难度的编程问题,即在给定数组中找到所有和为0的不重复三元组。提供的解决方案首先对数组进行排序,然后使用两层循环寻找目标和。在循环过程中,通过调整指针来避免重复元素,并在找到符合条件的三元组时将其添加到结果列表中。这种方法有效地解决了问题,避免了重复并优化了搜索过程。
5万+

被折叠的 条评论
为什么被折叠?



