JAVA solution using Collections.sort


  • 0
    R

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;

    public class Solution {
    public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {

         List<int[]> smallestSumTmp=new ArrayList<int[]>();
         List<int[]> smallestSum=new ArrayList<int[]>();
        //put all the combination to the first tmp list
       for(int i=0;i<nums1.length;i++)
         for(int j=0;j<nums2.length;j++)
        	 
         { int[] tmp={nums1[i],nums2[j]};
         
           smallestSumTmp.add(tmp);
          
         }
         
         
        //sort the list by override the abstract compare method 
       Collections.sort(smallestSumTmp, new Comparator<int[]>() {
     	@Override
    	public int compare(int[] o1, int[] o2) {
    		// TODO Auto-generated method stub
    		return (o1[0]+o1[1])-(o2[0]+o2[1]);
    	}
         });
       
       // put into the final list 
       if (smallestSumTmp.size()>0){
       for(int i=0;i<k;i++)
    	   if (i<smallestSumTmp.size())
    	      {smallestSum.add(smallestSumTmp.get(i));}
       }
        
       return  smallestSum;
            
        
        
    }
    

    }


Log in to reply
 

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