首页 > 代码库 > 15. 3Sum

15. 3Sum

https://leetcode.com/problems/3sum/#/description

http://www.cnblogs.com/EdwardLiu/p/4010951.html

 

public class Solution {
    public List<List<Integer>> threeSum(int[] num) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (num == null || num.length < 3) {
            return res;
        }
        Arrays.sort(num);
        for (int i=num.length-1; i>=2; i--) {
            if (i<num.length-1 && num[i]==num[i+1]) continue;
            twoSum(num, 0, i-1, -num[i], res, num[i]);
        }
        return res;
    }
    
    public void twoSum(int[] num, int l, int r, int target, List<List<Integer>> res, int lastInTriplet) {
        while (l < r) {
            if (num[l] + num[r] == target) {
                List<Integer> set = new ArrayList<Integer>();
                set.add(num[l]);
                set.add(num[r]);
                set.add(lastInTriplet);
                res.add(new ArrayList<Integer>(set));
                l++;
                r--;
                while (l<r && num[l]==num[l-1]) {
                    l++;
                }
                while (l<r && num[r]==num[r+1]) {
                    r--;
                }
            }
            else if (num[l] + num[r] > target) {   // 2 pointers 先sorting , 通过与零或target判断直接跳过不必要的选项.
                r--;
            }
            else {
                l++;
            }
        }
    }
}

  

15. 3Sum