[LeetCode] 3Sum

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

 

思路:

这道题其实就是two sum的加强版,麻烦的是去重复,用两个指针比较好。hash比较占空间。时间复杂度为O(n^2)。去重其实是分两步,第一步是如果target的前后两个一样,第二次就pass,这个方法决定第一次再找target的时候必须要找全。在找的时候,当一组解已经找到了,那么还要注意的情况是如果它的第一个指针的下一个或者最后一个指针的前一个都一样,要pass,因为只需要加入一次即可。

几个细节:

第一个因为需要等于0,所以从小到大排序以后如果当target大于0, 就break;

第二个如果initial 一个有parameter的arraylist -> new ArrayList<Integer>(Arrays.asList(a, b, c))

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> rst = new ArrayList<>();
        if (nums == null || nums.length < 3) return rst;
        Arrays.sort(nums);
        for (int t = 0; t < nums.length - 2; t++) {
            int target = nums[t];
            if (target > 0) break;
            if (t > 0 && nums[t - 1] == target) continue;
            int i = t + 1, j = nums.length - 1;
            while (i < j) {
                if (nums[i] + nums[j] < -target) i++;
                else if (nums[i] + nums[j] > -target) j--;
                else {
                    List<Integer> list = new ArrayList<Integer>(Arrays.asList(nums[t], nums[i], nums[j]));
                    rst.add(list);
                    while (i < j && nums[i] == nums[i + 1]) i++;
                    while (i < j && nums[j] == nums[j - 1]) j--;
                    i++;
                    j--;
                }    
            }
            
        }
        return rst;
    }
}

 

posted on 2018-03-20 10:43  codingEskimo  阅读(97)  评论(0编辑  收藏  举报

导航