668 Kth Smallest Number in Multiplication Table
1. Question
Nearly every one have used the Multiplication Table. But could you find out thek-thsmallest number quickly from the multiplication table?
Given the heightmand the lengthnof am * nMultiplication Table, and a positive integerk, you need to return thek-thsmallest number in this table.
Example 1:
Input: m = 3, n = 3, k = 5
Output:
Explanation:
The Multiplication Table:
1 2 3
2 4 6
3 6 9
The 5-th smallest number is 3 (1, 2, 2, 3, 3).Example 2:
Note:
The
mandnwill be in the range [1, 30000].The
kwill be in the range [1, m * n]
2. Implementation
(1) Binary Search
思路: Kth Smallest Element in a Sorted Matrix 一样的解法
(2) Heap
3. Time & Space Complexity
Binary Search: 时间复杂度O((m+n)log(mn)), 空间复杂度O(1)
Heap: 时间复杂度O(m * n * logn), 空间复杂度O(logn), heap存储最多n个(列数)个数
Last updated
Was this helpful?