Given two integer arrays sorted in ascending order and an integer k. Define sum = a + b, where a is an element from the first array and b is an element from the second one. Find the kth smallest sum out of all possible sums.
Example
Given [1, 7, 11] and [2, 4, 6].
For k = 3, return 7.
For k = 4, return 9.
For k = 8, return 15.
Challenge
Do it in either of the following time complexity:
O(k log min(n, m, k)). where n is the size of A, and m is the size of B.
O( (m + n) log maxValue). where maxValue is the max number in A and B.
Tags
Heap Priority Queue Sorted Matrix
Related Problems
Medium Kth Smallest Number in Sorted Matrix
Medium Search a 2D Matrix II
Analysis
此题乍看似乎没有很好的思路,其实稍加转化就变成了熟悉的问题:Kth Smallest Number in Sorted Matrix.
classNode {publicint x, y, sum;publicNode(int x,int y,int sum) {this.x= x;this.y= y;this.sum= sum; }}classNodeComparatorimplementsComparator<Node> { @Overridepublicintcompare(Node a,Node b) {returna.sum-b.sum; }}publicclassSolution {int[] dx =newint[] {0,1};int[] dy =newint[] {1,0};// Check if a coordinate is valid and should be marked as visitedpublicbooleanisValid(int x,int y,int[] A,int[] B,boolean[][] visited) {if (x <A.length&& y <B.length&&!visited[x][y]) {returntrue; }returnfalse; } /** * @param A an integer arrays sorted in ascending order * @param B an integer arrays sorted in ascending order * @param k an integer * @return an integer */publicintkthSmallestSum(int[] A,int[] B,int k) {// Validation of inputif (A ==null|| B ==null||A.length==0||B.length==0) {return-1; }if (A.length*B.length< k) {return-1; }PriorityQueue<Node> heap =newPriorityQueue<Node>(k,newNodeComparator());heap.offer(newNode(0,0,A[0] +B[0]));boolean[][] visited =newboolean[A.length][B.length];for (int i =0; i < k -1; i++) {Node smallest =heap.poll();for (int j =0; j <2; j++) {int nextX =smallest.x+ dx[j];int nextY =smallest.y+ dy[j];if (isValid(nextX, nextY, A, B, visited)) { visited[nextX][nextY] =true;int nextSum =A[nextX] +B[nextY];heap.offer(newNode(nextX, nextY, nextSum)); } } }returnheap.peek().sum; }}