015 3Sum 三个数的和为目标数字

Given an array S of n integers, are there elements a, b, c in S 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.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
详见:https://leetcode.com/problems/3sum/description/
实现语言:Java
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        int target=0;
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        int size=nums.length;
        if(size<3||nums==null){
            return res;
        }
        Arrays.sort(nums);
        for(int i=0;i<size-2;++i){
            if(i>0&&nums[i]==nums[i-1]){
                continue;
            }
            int l=i+1;
            int r=size-1;
            while(l<r){
                int sum=nums[i]+nums[l]+nums[r];
                if(sum<target){
                    while(l<r&&nums[++l]==nums[l-1]);
                }else if(sum>target){
                    while(l<r&&nums[--r]==nums[r+1]);
                }else{
                    List<Integer> tmp=new ArrayList<Integer>();
                    tmp.add(nums[i]);
                    tmp.add(nums[l]);
                    tmp.add(nums[r]);
                    res.add(tmp);
                    while(l<r&&nums[++l]==nums[l-1]);
                    while(l<r&&nums[--r]==nums[r+1]);
                }
            }
        }
        return res;
    }
}

 

posted on 2018-02-27 17:00  lina2014  阅读(139)  评论(0编辑  收藏  举报

导航