3Sum, Leetcode 解题笔记

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.

经典题目,先排序array,利用a+b=-c,遍历array,使每次的integer = -c,从两头寻找a和b使得a+b=-c。主要难点在于duplicate solution的处理。此解法复杂度为O(n^2)。

public class Solution {
    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        Arrays.sort(num);
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        for(int i = 0; i < num.length; i++){
            
            //avoid duplicate solutions
            if(i == 0 || num[i] > num[i-1]){
                int target = -num[i];
                int left = i + 1;
                int right = num.length-1;
                while(left < right){
                    if(num[left] + num[right] < target){
                        left++;
                    }
                    else if(num[left] + num[right] > target){
                        right--;
                    }
                    else{
                        ArrayList<Integer> l = new ArrayList<Integer>();
                        l.add(num[i]);
                        l.add(num[left]);
                        l.add(num[right]);
                        ret.add(l);
                        left++;
                        right--;
                        
                        //avoid duplicate solutions
                        while(left < right && num[left] == num[left-1]){
                            left++;
                        }
                        while(left < right && num[right] == num[right+1]){
                            right--;
                        }
                    }
                }
            }
        }
        return ret;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s