Description:
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]
]
题意:给定一个整型数组,在数组中找出三个数,使其和为0;
解法:对于x+y+z=0来说,要找到三个数之和为0,即找到两个数之和满足x+y=-z;因此,对于第一个数来说,如果已经大于0了,那么肯定不存在另外两个数使其满足条件了;除了特殊情况的[0,0,0]来说,第一个数为负数,后面要找的两个数之和为第一个数的负数,另其为target,那么第二个数x我们可以从其后一个位置开始往后找,而第三个数y从数组的末尾开始找,这个时候会有三种情况:
- if x+y == target,满足条件
- if x+y > target,说明相加的数字过大,那么末尾的那个数可以向前遍历
- if x+y < target,说明相加的数字过小,那么第二个数可以向后遍历
要注意的是需要考虑得到重复的结果,因此我们需要跳过相同数字的情况;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
Arrays.sort(nums);
for(int i=0; i<nums.length; i++){
if(nums[i] > 0) break;
if(i > 0 && nums[i] == nums[i-1]) continue;//跳过重复的数字
int st = i + 1;
int ed = nums.length - 1;
int target = 0 - nums[i];//剩余的两数之和
while(st < ed){
if(nums[st] + nums[ed] == target){
List<Integer> x = new LinkedList<>();
x.add(nums[i]);
x.add(nums[st]);
x.add(nums[ed]);
result.add(x);
//跳过重复的数字
while(st < ed && nums[st] == nums[st + 1]) st++;
while(st < ed && nums[ed] == nums[ed - 1]) ed--;
st++;
ed--;
}
else if(nums[st] + nums[ed] > target) ed--;
else st++;
}
}
return result;
}
}