Slow but easy to read and easy to maintain solution


  • 0
    D
    public class Solution {
    	public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
    
    		List<PairNum> combinations = new ArrayList<PairNum>();     
    		for(int i =0;i<nums1.length;i++){
    			for(int y =0;y<nums2.length;y++){
    				combinations.add(new PairNum(nums1[i], nums2[y]));
    			}	
    		}
    		
    		Collections.sort(combinations);
    		List<int[]> result = new ArrayList<int[]>();
    		for (int i =0;i<combinations.size()&&i<k;i++){
    			result.add(combinations.get(i).getArrayPair());
    			
    		}
    		return result;
    	}
    	class PairNum implements Comparable<PairNum>{
    		private int i;
    		private int y;
    
    		PairNum(int i,int y){
    			this.i = i;
    			this.y = y;
    				
    		}
    		private int sum() {
    			return i+y;
    
    		}
    		public int[] getArrayPair(){
    			
    		    return new int[]{i,y};
    			
    		}
    		@Override
    		public String toString() {
    		
    			return sum()+"";
    		}
    		@Override
    		public int compareTo(PairNum o) {
    			  if (this.sum() == o.sum())
    		            return 0;
    		        else if ((this.sum()) > o.sum())
    		            return 1;
    		        else
    		            return -1;
    		}
    		
    	}
    }
    
    
    

Log in to reply
 

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