Clean java solution


  • 0
    Z

    public class Solution {
    public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
    List<int[]> ans = new ArrayList<>(k);
    int m = nums1.length, n = nums2.length, i, j;

        Queue<int[]> pq = new PriorityQueue<>(k , new Comparator<int[]>(){
            public int compare(int[] p1, int[] p2) {
                return p2[0] + p2[1] - p1[0] - p1[1];
            }    
        });
        
        for(i=0;i<m;i++) {
            for(j=0;j<n;j++) {
                if(pq.size() < k) {
                    pq.add(new int[]{nums1[i] , nums2[j]});
                } else {
                    int[] peek = pq.peek();
                    
                    if(peek[0] + peek[1] > nums1[i] + nums2[j]) {
                        pq.poll();
                        pq.add(new int[]{nums1[i] , nums2[j]});
                    }
                }
            }
        }
        
        while(!pq.isEmpty()) {
            ans.add(pq.poll());
        }
        
        Collections.reverse(ans);
        return ans;
    }
    

    }


Log in to reply
 

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