3Sum

Two pointers

public class Solution {
    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        Arrays.sort(num);
        int length = num.length;
        
        for(int i = 0; i< length; i++){
            int start = i+1;
            int end = length -1;
            int target = 0 - num[i];
            
            while (start< end){
                if(target == num[start] + num[end]){
                    ArrayList<Integer> list = new ArrayList<Integer>();
                    list.add(num[i]);
                    list.add(num[start]);
                    list.add(num[end]);
                    result.add(list);
                    start++;
                    end--;
    /*filter the duplicate during two-pointer scan. For example [-2, 0, 0, 2,2], the expected output should be [-2,0,2]. If no filter here, the output will be duplicate as [-2,0,2] and [-2,0,2] */
                    while(num[start] == num[start-1] && start < end){
                        start++;
                    }
                    
                    while(num[end] == num[end+1] && start < end){
                        end--;
                    }
                    
                }else if(target > num[start] + num[end]){
                    start++;
                }else {
                    end--;
                }
                
            }
            //filter the duplicate for outside iteration. For example [-2, -2, -2, 0,2]. 最后一个是i+1,所以是i<length -1 
             while((i< length-1) && num[i] == num[i+1]){
                 i++;
             }
            
            
           
        }
        return result;
    }
}
        

 

posted @ 2014-01-25 17:25  Razer.Lu  阅读(167)  评论(0编辑  收藏  举报