My java solution


  • 3
    X
    public class Solution {
        public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
            
            ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
            if(num==null ||num.length<3){
                return result;
            }
            
            int length = num.length;
            Arrays.sort(num);
            
            for(int i=0;i<length;i++){
                int left = i+1;
                int right = length-1;
                while(left<right){
                    int sum = num[i] + num[left] + num[right];
                    if(sum==0){
                        ArrayList<Integer> result2 = new ArrayList<Integer>();
                        result2.add(num[i]);
                        result2.add(num[left]);
                        result2.add(num[right]);
                        result.add(result2);
                        left++;
                        right--;
                        while(left<right&&num[left]==num[left-1]){
                            left++;
                        }
                        while(left<right&&num[right]==num[right+1]){
                            right--;
                        }
                    }else if(sum<0){
                        left++;
                    }else{
                        right--;
                    }
                }
            }
            HashSet hs = new HashSet();
            hs.addAll(result);
            result.clear();
            result.addAll(hs);
            return result;
        }
    }

  • 0
    Z
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.