Find K Pairs with Smallest Sums

来源:互联网 发布:matlab中值滤波算法 编辑:程序博客网 时间:2024/06/11 02:38

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 = 3Return: [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 = 2Return: [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]
思路:跟 Kth Smallest Element is Sorted Matrix 是一个原理,唯一注意的一点就是,题目可以要求k > num1.length*num2.length, 也就是要前100个,只有60个,那么返回的list也要装60个元素,也就是最后pq的size需要判断一下,pq.size()>0 .

public class Solution {        class Node{        int x;        int y;        int val;        public Node(int x, int y, int val){            this.x = x;            this.y = y;            this.val = val;        }    }        public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {        List<int[]> list = new ArrayList<int[]>();        if(nums1 == null || nums2==null || nums1.length == 0 || nums2.length == 0 ) return list;        int[][] matrix = new int[nums1.length][nums2.length];        for(int i=0; i<nums1.length; i++){            for(int j=0; j<nums2.length; j++){                matrix[i][j] = nums1[i] + nums2[j];            }        }                findKSmallestPair(matrix, list, k, nums1, nums2);        return list;    }        public void findKSmallestPair(int[][] matrix, List<int[]> list, int k, int[] nums1, int[] nums2){        PriorityQueue<Node> pq = new PriorityQueue<Node>(k, new Comparator<Node>(){           @Override           public int compare(Node a, Node b){               return a.val - b.val;           }        });                for(int i=0; i<matrix[0].length; i++){            pq.add(new Node(0,i,matrix[0][i]));        }                int count = 0;        while(count<k && pq.size()>0){            Node node = pq.poll();            count++;            int x = nums1[node.x];            int y = nums2[node.y];            list.add(new int[]{nums1[node.x], nums2[node.y]});                        if(count >= k){                 break;            }            if(node.x+1<matrix.length){                pq.add(new Node(node.x+1, node.y, matrix[node.x+1][node.y]));            }        }    }}


0 0
原创粉丝点击