Monday, April 17, 2017

[LintCode] 57 3Sum 解题报告

Description
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.


Notice
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)

The solution set must not contain duplicate triplets.



Example
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is:

(-1, 0, 1)
(-1, -1, 2)



思路
先排序,然后遍历数组,对于每一个元素,求这个数负值的twoSum。
要注意数组重复的数的处理。


Code
public class Solution {
    /**
     * @param numbers : Give an array numbers of n integer
     * @return : Find all unique triplets in the array which gives the sum of zero.
     */
    public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) {
        // write your code here
        
        ArrayList<ArrayList<Integer>> results = new ArrayList<>();
        
        if (numbers == null || numbers.length < 3) {
            return results;
        }
        
        Arrays.sort(numbers);
        
        for (int i = 0; i < numbers.length - 2; i++) {
            if (i > 0 && numbers[i] == numbers[i - 1]) {
                continue;
            }
            int target = -numbers[i];
            int left = i + 1;
            int right = numbers.length - 1;
            twoSum(numbers, left, right, target, results);
        }
        
        return results;
    }
    
    public void twoSum(int[] nums, 
                       int left, 
                       int right, 
                       int target, 
                       ArrayList<ArrayList<Integer>> results) {
                           
        while (left < right) {
            if (nums[left] + nums[right] == target) {
                ArrayList<Integer> tuple = new ArrayList<>();
                tuple.add(-target);
                tuple.add(nums[left]);
                tuple.add(nums[right]);
                results.add(tuple);
                left++;
                right--;
                
                while (left < right && nums[left] == nums[left - 1]) {
                    left++;
                }
                while (right > left && nums[right] == nums[right + 1]) {
                    right--;
                }
                
            }
            else if (nums[left] + nums[right] > target) {
                right--;
            }
            else {
                left++;
            }
            
        }
    }
}