2014年5月12日星期一

Loop Approach Solution - 3Sum

The idea is to convert this to two number sum question by add one outside loop. To avoid duplicates by comparing with previous (0 case excluded as -1). Sort is must have before all operations.

Loop condition is another factor, and how it loops. Only loop after current out side index is sufficient.

public class Solution {
    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        if(num == null || num.length < 3){
            return new ArrayList<ArrayList<Integer>>();
        }
        ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
        Arrays.sort(num);
        for(int i = 0; i < num.length - 2; i++){
            if (i > 0 && num[i] == num[i - 1]) {
continue;
}
            int curTar = 0 - num[i];
            int start = i + 1;
            int end = num.length - 1;
            while(start < end){
                if(num[start] + num[end] > curTar){
                    end--;
                }else if(num[start] + num[end] < curTar){
                    start++;
                }else{
                    ArrayList<Integer> result = new ArrayList<Integer>();
                    result.add(num[i]);
                    result.add(num[start]);
                    result.add(num[end]);
                    results.add(result);
                    while(++start< --end && num[start] == num[start - 1] && num[end] == num[end + 1]);
                }
            }
        }
        return results;
    }
}

没有评论: