3Sum N2 Java Solution


  • 0
    S

    class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
    int[] arr=nums;
    Arrays.sort(arr);
    List<List<Integer>> listOfSums=new ArrayList<List<Integer>>();
    for (int i = 0; i < arr.length; i++) {
    int start=i+1;
    int end=arr.length-1;
    if(i==0 || arr[i]!=arr[i-1]){
    while(start<end){
    List<Integer> sumList=new ArrayList<Integer>();
    int sum=arr[i]+arr[start]+arr[end];
    if(sum==0){
    sumList.add(arr[i]);
    sumList.add(arr[start]);
    sumList.add(arr[end]);
    listOfSums.add(sumList);
    }
    if(sum<0){
    int currStart=start;
    while(arr[currStart]==arr[start]&& start<end){
    start++;
    }
    }else{
    int currEnd=end;
    while(arr[end]==arr[currEnd]&& start<end){
    end--;
    }
    }
    }
    }
    }

    	 return listOfSums;
    
    }
    

    }


Log in to reply
 

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