题目地址:
https://www.lintcode.com/problem/kth-smallest-number-in-multiplication-table/description
给定一个 m × n m\times n m×n的乘法表,求其第 k k k小的数。
思路是二分答案。我们需要找的数 n n n应当满足,它是最小的满足小于等于 n n n的数不少于 k k k个的数。因此可以用二分。详细说明参考https://blog.csdn.net/qq_46105170/article/details/109379551。代码如下:
public class Solution {
/**
* @param m: a integer
* @param n: a integer
* @param k: a integer
* @return: return a integer
*/
public int findKthNumber(int m, int n, int k) {
// write your code here
int l = 1, r = m * n;
while (l < r) {
int mid = l + (r - l >> 1);
// 求小于等于mid的数有多少个
int count = 0;
int x = m, y = 1;
while (x >= 1 && y <= n) {
if (x * y <= mid) {
count += x;
y++;
} else {
x--;
}
}
if (count >= k) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
时间复杂度 O ( ( m + n ) log ( m n ) ) O((m+n)\log (mn)) O((m+n)log(mn))。