/**
* 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 = []
输出:[]
链接:https://leetcode-cn.com/problems/3sum
*/
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<>();
for(int first = 0; first < n; ++first) {
if(first > 0 && nums[first] == nums[first - 1]) {
continue;
}
int target = -nums[first];
int second = first + 1;
int third = n -1;
while(second < third){
if(second > first + 1 && nums[second] == nums[second - 1]){
second++;
continue;
}
if(third < n - 1 && nums[third + 1] == nums[third]){
third--;
continue;
}
int tmp = nums[third] + nums[second];
if(tmp > target){
third--;
}else if(tmp < target){
second++;
}else{
List<Integer> tmp_list = new ArrayList<>();
tmp_list.add(nums[first]);
tmp_list.add(nums[second]);
tmp_list.add(nums[third]);
ans.add(tmp_list);
second++;
}
}
}
return ans;
}
}
15. 三数之和(双指针)
最新推荐文章于 2025-11-24 14:44:53 发布
该博客详细介绍了如何解决LeetCode上的经典问题——三数之和。通过排序数组并使用双指针法,有效地找到数组中所有和为0的不重复三元组。示例展示了对于不同输入(包括空数组)的处理方法。
497

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



