Some problem about "https://leetcode.com/problems/3sum/"


  • 0
    Z

    //I cann't be sure that,the array result need be sorted???
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;
    /*

    • For example, given array S = [-1, 0, 1, 2, -1, -4],
      A solution set is:
      [
      [-1, 0, 1],
      [-1, -1, 2]
      ]
      */
      public class ThreeSum {
      public static List<List<Integer>> threeSum(int[] nums) {

       Set<List<Integer>> lists=new HashSet<List<Integer>>();
       ArrayList<List<Integer>> list=new ArrayList<List<Integer>>();
       nums=sortArray(nums);
       
       for(int i=0;i<nums.length;i++){
           
           int tempI=nums[i];
           
           for(int j=i+1;j<nums.length;j++){
               
               int tempJ=nums[j];
               
               for(int k=j+1;k<nums.length;k++){
                   
                   if(tempI+tempJ+nums[k]==0){
                       List<Integer> tempList=new ArrayList<Integer>();
                       tempList.add(tempI);
                       tempList.add(tempJ);
                       tempList.add(nums[k]);
                       lists.add(tempList);
                   }                    
               }
           }
           
       }
       
      Iterator<List<Integer>> iterator=lists.iterator();
      while(iterator.hasNext()){
        list.add(iterator.next());
      }
      return list;
      

      }

      public static int[] sortArray(int[] nums){

      for(int i=0;i<nums.length;i++){
      	for(int j=0;j<nums.length-i-1;j++){
      		if(nums[j]>nums[j+1]){
      			int temp=nums[j];
      			nums[j]=nums[j+1];
      			nums[j+1]=temp;
      		}
      	}
      }
      return nums;
      

      }

      public static void main(String[] args) {
      int []nums={7,-10,7,3,14,3,-2,-15,7,-1,-7,6,-5,-1,3,-13,6,-15,-10,14,8,5,-10,-1,1,1,11,6,8,5,-4,0,3,10,-12,-6,-2,-6,-6,-10,8,-5,12,10,1,-8,4,-8,-8,2,-9,-15,14,-11,-1,-8,5,-13,14,-2,0,-13,14,-12,12,-13,-3,-13,-12,-2,-15,4,8,4,-1,-6,11,11,-7,-12,-2,-8,10,-3,-4,-6,4,-14,-12,-5,0,3,-3,-9,-2,-6,-15,2,-11,-11,8,-11,8,-7,8,14,-5,4,10,3,-1,-15,10,-6,-11,13,-5,1,-15};
      List<List<Integer>> lists=threeSum(nums);
      for(int i=0;i<lists.size();i++){
      System.err.println(lists.get(i));
      }
      }

    }


Log in to reply
 

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