最后一遍-L15-3Sum
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]
]
理解题意: 理解没有重复的triplet的意思 Array two index,
代码:
class Solution {
// 主要的在于排序,关键的点,在于去重
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result= new ArrayList<List<Integer>>();
// first sort
Arrays.sort(nums);
for(int i =0 ; i < nums.length-2; i++){
for(int j = i+1,k=nums.length-1 ; k>j;){
if(nums[i]+nums[j]+nums[k] == 0){
List<Integer> tmpresult = Arrays.asList(nums[i],nums[j],nums[k]);
result.add(tmpresult);
j++;
k--;
}else if(nums[i]+nums[j]+nums[k]> 0){
k--;
}else{
j++;
}
}
}
return result;
}
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(nums == null|| nums.length <3) return result;
Arrays.sort(nums);
//two point interation
for (int i = 0; i < nums.length - 2; i++) {
if(i > 0 && nums[i] == nums[i-1]) continue;
int j=i+1,k=nums.length-1;
while(j < k){
if(j>i+1 && nums[j-1] == nums[j]){
j++;
continue;
}
int sum = nums[i]+nums[j]+nums[k];
if(sum==0){
result.add(Arrays.asList(nums[i],nums[j],nums[k]));
j++;
k--;
}else if(sum>0){
k--;
}else{
j++;
}
}
}
return result;
}
}