3sum

 

Given an array nums of n integers, are there elements abc 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]
]

思路:sort之后,三指针移动,主要是去重复。
i 去重复,就想着,i和i-1如果一样,那后面的j和k的组合,可能就会有重复的。所以i==i-1的时候continue
j,k去重复,sum=0之后,j++,k--,重点是同时移动,如果j==j-1,k==k+1,则不需要加入,继续走;
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> lists = new ArrayList<List<Integer>>();
        if(nums == null || nums.length <=2) return lists;
        
        Arrays.sort(nums);
        for(int i=0; i<nums.length-2; i++) {
            int j=i+1; int k=nums.length-1;
            if(i-1 >=0 && nums[i] == nums[i-1]){
                continue;
            }
            while(j<k){
                int sum = nums[i] + nums[j] + nums[k];
                if(sum == 0) {
                    List<Integer> list = new ArrayList<Integer>();
                    list.add(nums[i]);
                    list.add(nums[j]);
                    list.add(nums[k]);
                    lists.add(list);
                    j++;
                    k--;
                    while(k>=0 && j<nums.length-1 && nums[j] == nums[j-1] && nums[k] == nums[k+1]){
                        j++;
                        k--;
                    }
                }else if(sum < 0) {
                    j++;
                } else {
                    k--;
                }
            }  
        }
        return lists;
    }
}

  

posted @ 2018-08-04 13:13  硅谷雷神  阅读(82)  评论(0)    收藏  举报