Three Sum solution in Java


  • 0
    W

    public static List<List<Integer>> threeSum(int[] nums) {
    Arrays.sort(nums);
    List arrays= new ArrayList();

          for(int i=0;i<nums.length-2;i++){
    			 for(int j=i+1;j<nums.length-1;j++){
    				 for(int k=j+1;k<nums.length;k++){
    					int sum=nums[i]+nums[j]+nums[k];
    					 List<Integer> array=new ArrayList();
    					if(sum==0){
                            array.add(nums[i]);
    						array.add(nums[j]);
    						array.add(nums[k]);		           
    	         	        arrays.add(array);          
    					  }						
    				 }					 
    		     }
    	  }
          for(int n=1;n<arrays.size();n++){
        	if(((List) arrays.get(n)).equals((List) arrays.get(n-1))){
        		arrays.remove(n-1);
        	};
         }
         
    	 return arrays;    
      
       
        }

Log in to reply
 

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