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:

  • 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.
    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)

解题思路:

类似 Leetcode Two Sum II - Input array is sorted  O(n^2)

The inner three while loops ensure that if there are duplicate numbers, only one of the duplicate number is added to the solution.

Suppose the array is [2, 2, 5, 9, -7]

When i = 0, low = 2, high = 4, the sum would be 0 and hence the solution would be added to the list. Now if we don't have these while loops and we let the for loop increment i to 1, we will once again get the same solution since 2 appears twice in the array.


Java code

public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        for(int i = 0; i < nums.length; i++){
            int low = i+1;
            int high = nums.length-1;
            while(low < high){
                if(nums[i] + nums[low] + nums[high] == 0){
                    result.add(Arrays.asList(nums[i], nums[low], nums[high]));
                    while(i + 1 < nums.length && nums[i+1] == nums[i]) {
                        i++;
                    }
                    while(low + 1 < nums.length && nums[low+1] == nums[low]) {
                        low++;
                    }
                    while(high -1 >= 0 && nums[high] == nums[high-1]) {
                        high--;
                    }
                    low++;
                    high--;
                }else if(nums[i]+nums[low]+nums[high]>0) {
                    high--;
                }else {
                    low++;
                }
            }
        }
        return result;
    }
}

Reference:

1. https://leetcode.com/discuss/51713/clean-java-o-n-2-solution-using-two-pointers

 

posted @ 2015-10-17 03:26  茜茜的技术空间  阅读(247)  评论(0编辑  收藏  举报