Saturday, December 24, 2016

373. Find K Pairs with Smallest Sums

You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
Define a pair (u,v) which consists of one element from the first array and one element from the second array.
Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.
Example 1:
Given nums1 = [1,7,11], nums2 = [2,4,6],  k = 3

Return: [1,2],[1,4],[1,6]

The first 3 pairs are returned from the sequence:
[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
Example 2:
Given nums1 = [1,1,2], nums2 = [1,2,3],  k = 2

Return: [1,1],[1,1]

The first 2 pairs are returned from the sequence:
[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
Example 3:
Given nums1 = [1,2], nums2 = [3],  k = 3 

Return: [1,3],[2,3]

All possible pairs are returned from the sequence:
[1,3],[2,3]

A:

自己看下面的解法有什么问题,啊哈哈

public class Solution {
    public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        List<int[]> res = new LinkedList();
        int i = 0,j=0, m = nums1.length, n = nums2.length;
        k = Math.min(k,m*n);
        while(k-- >= 0){
            int[] tmp = {nums1[i],nums2[j]};
            res.add(tmp);
            if(i==m-1){
                j++;
            }else if(j==n-1){
                i++;
            }else{
                if(nums1[i+1]+nums2[j] < nums1[i]+nums2[j+1])
                    i++;
                else
                    j++;
            }
        }
        return res;
    }
}


-------Use priority heap----------

public class Solution {
    public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        List<int[]> res = new LinkedList();
        int m = nums1.length, n = nums2.length;
        if(m==0 || n == 0 || k <=0)
            return res;
        int[] index = new int[m];// for nums1
        PriorityQueue<int[]> minHeap = new PriorityQueue<>(m, (A, B) -> A[1] + A[2] - B[1] - B[2]);
        for(int i = 0;i<m;i++)  // put the initial values
            minHeap.offer(new int[]{i, nums1[i], nums2[0]});
        while( !minHeap.isEmpty() && k-- > 0){
            int[] top = minHeap.poll();
            res.add(new int[]{top[1], top[2]});
            int t = top[0]; // index of which element of nums1 is used.
            if(index[t] +1 < n)//if next move on nums2 is also valid,
                minHeap.add( new int[]{t, nums1[t], nums2[++index[t]]} );
        }
            return res;
        }
    }



Error:

没有考虑Example 3的情况,没有读完题意呀,😌

Java Lambda to write a comparator

clearly to understand how make a minHeap and maxHeap in the Compare method()


No comments:

Post a Comment