15. 3Sum

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

Solution

注意点:
两处去重

Complexity

O(n2) O(n)

Code

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for(int i = 0; i < nums.length - 2; i++){
            int c = nums[i];
            int lo = i+1, hi = nums.length - 1;
            if(i > 0 && nums[i] == nums[i-1])
                continue;
            while(lo < hi){
                int sum = nums[lo] + nums[hi];
                if(sum == -c){
                     List<Integer> tmp = new ArrayList<>();
                    tmp.add(c);tmp.add(nums[lo]);tmp.add(nums[hi]);
                    res.add(tmp);
                    while( lo < hi && nums[lo + 1] == nums[lo]) lo++;
                    lo++;hi--;
                }else if(sum < -c){
                    lo++;
                }else{
                    hi--;
                }
            }
        }
        return res;
    }
}