# leetcode-15. 三数之和

给定数组 nums = [-1, 0, 1, 2, -1, -4]，

[
[-1, 0, 1],
[-1, -1, 2]
]


## 解法一：借助2sum

**思路：**注意去重

import java.util.*;
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);
if(nums[0]>0) return res;
for(int i=0;i<nums.length-2;i++){
if(i>0&&nums[i]==nums[i-1]) continue;
List<List<Integer>> tmp = twoSum(nums,i+1,-nums[i]);
if(tmp.size()!=0){
for(List<Integer> l:tmp){
}
}
}
return res;
}
public List<List<Integer>> twoSum(int[] numbers, int index, int target) {
List<List<Integer>> res = new ArrayList<>();
if(numbers==null||numbers.length<2) return res;
int i=index;
int j=numbers.length-1;
while(i<j){
if(i>index&&numbers[i]==numbers[i-1]){
i++;
}else if(numbers[i]+numbers[j]==target){
List<Integer> tmp = new ArrayList<>();
i++;
j--;
}else if(numbers[i]+numbers[j]<target){
i++;
}else{
j--;
}
}
return res;
}
}


## 解法二：直接三指针

**思路：**其实和上边一样

import java.util.*;
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);
if(nums[0]>0) return res;
for(int i=0;i<nums.length-2;i++){
if(i>0&&nums[i]==nums[i-1]) continue;
int l=i+1;
int r=nums.length-1;
int target = -nums[i];
while(l<r){
if(l>i+1&&nums[l]==nums[l-1]){
l++;
}else if(nums[l]+nums[r]==target){
List<Integer> tmp = new ArrayList<>();
l++;
r--;
}else if(nums[l]+nums[r]<target){
l++;
}else{
r--;
}
}
}
return res;
}
}


©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客