Level:
??Medium
题目描述:
Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路分析:
?求数组中三数和为零的情况,首先我们将数组进行排序,然后遍历数组,设置两个指针left和right,访问到节点i的时候,将left设置为i+1,right设置为nums.length-1。然后看nums[left]和nums[right]的和是否为-nums[i],如果是,那么就找到一组满足要求的解,如果不能则移动left和right,直到相等。
? 注意要避免重复的情况
代码:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>>res=new ArrayList<>();
if(nums==null||nums.length<3)
return res;
Arrays.sort(nums); //进行排序
for(int i=0;i<nums.length;i++){
int towsum=-nums[i];
int left=i+1;
int right=nums.length-1;
while(left<right){
if(nums[left]+nums[right]==towsum){
res.add(Arrays.asList(nums[i],nums[left],nums[right]));
left++;
while(left<nums.length&&nums[left]==nums[left-1])
left++; //避免出现重复情况
right--;
while(right>=0&&nums[right]==nums[right+1])
right--; //避免出现重复情况
}
else if(nums[left]+nums[right]<towsum){
left++;
}
else{
right--;
}
}
while(i<nums.length-1&&nums[i]==nums[i+1])
i++; //避免出现重复情况
}
return res;
}
}
原文地址:https://www.cnblogs.com/yjxyy/p/10744600.html
时间: 2024-11-10 13:20:03