668. Kth Smallest Number in Multiplication Table
Similar to #378: http://localhost:4000/2018/06/21/LeetCode-Challenge-log-378/, except now we can count how many smaller faster in O(n) time! There is also two tricks to achieve 99% beaten:
- Switch m and n if m > n. So it can count faster
- Do not use build-in min() but if statement. Too many function calls slows down the speed.
Nearly every one have used the Multiplication Table. But could you find out the k-th
smallest number quickly from the multiplication table?
Given the height m
and the length n
of a m * n
Multiplication Table, and a positive integer k
, you need to return the k-th
smallest number in this table.
Example 1:
1 | Input: m = 3, n = 3, k = 5 |
Example 2:
1 | Input: m = 2, n = 3, k = 6 |
Note:
- The
m
andn
will be in the range [1, 30000]. - The
k
will be in the range [1, m * n]
Soulution:
1 | from heapq import * |