465. Kth Smallest Sum In Two Sorted Arrays
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.
假设 (i, j) 指 A[i] + A[j], 那么(i, j)的下一个元素为(i + 1, j)或(i, j + 1).
- 将(0, 0)加入最小堆,并用HashSet记录位置,
- 将堆顶元素出堆,得到其位置(i,j), 并将(i + 1, j)和(i, j + 1)入堆,HashSet记录位置. 入堆的时候要检查该元素是否入过堆,及坐标不得越界
- 重复step 2, k - 1次
- 返回堆顶
|
|