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]
]
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
//先把数组排序
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++){
//跳过重复的,因为结果一定会一样
if(i!=0 && nums[i]==nums[i-1]){
continue;
}
int key = 0-nums[i];
int j=i+1;
int e=nums.length-1;
while(j<e){
if(nums[j]+nums[e]==key){
//当前有一个结果,加到最终结果里
res.add(Arrays.asList(nums[i],nums[j],nums[e]));
j++;
while(nums[j]==nums[j-1] && j<e){
j++;
}
}
else if(nums[j]+nums[e]<key){
j++;
}else {
e--;
}
}
}
return res;
}
}
KEYPOINT
未排序,所以先排序Arrays.sort(nums);
注意要
if(i!=0 && nums[i]==nums[i-1]){
continue;
}
while(nums[j]==nums[j-1] && j<e){
j++;
}
跳过重复的,结果里不能重复
这样加方便点
但其实Arrays.asList适合对象,不适合基本类型
res.add(Arrays.asList(nums[i],nums[j],nums[e]));