IncredibleThings

导航

LeetCOde-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]
]

我们可以先固定一个数,然后找另外两个数之和为第一个数的相反数就可以了。

public class Solution {
     List<List<Integer>> resList=new LinkedList<>();
    public List<List<Integer>> threeSum(int[] nums) {
    
        if(nums==null || nums.length==0){
            return resList;
        }
        Arrays.sort(nums);
        int len=nums.length;
        if(nums[0]>0){
            return resList;
        }
        else if(nums[len-1]<0){
            return resList;
        }
        else{
            for(int i=0; i<nums.length-2; i++){
                if(!(i>0 && nums[i]==nums[i-1])){
                    findTwoNumbers(nums,nums[i],i+1);
                }
            }
        }
        return resList;
    }

    public void findTwoNumbers(int[] nums, int target, int start){
        int left=start;
        int right=nums.length-1;
        while(left<right){
            boolean isUnique=true;
            if(left!=start && nums[left]==nums[left-1]){
                left++;
                isUnique=false;
            }
            if(right!=nums.length-1 && nums[right]==nums[right+1]){
                right--;
                isUnique=false;
            }
            if(isUnique){
                if(nums[left]+nums[right]==(0-target)){
                    List<Integer> list=new ArrayList<Integer>();
                    list.add(target);
                    list.add(nums[left]);
                    list.add(nums[right]);
                    resList.add(list);
                    left++;
                    right--;
                }
                else if(nums[left]+nums[right]>(0-target)){
                     right--;
                }
                else{
                    left++;
                }
            }
        }
    }
    
    
}

 

posted on 2016-07-21 03:10  IncredibleThings  阅读(129)  评论(0编辑  收藏  举报