题目地址:https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/description/
题目描述: 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:
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).
我的代码:
class Solution {
public:
int findKthNumber(int m, int n, int k) {
if(m<n){
int t=n;
n=m;
m=t;
}
int s=1,e=k;
while(s!=e){
int x=0;
int b=(s+e)/2;
for(int i=1;i<=n&&i<=b;i++){
if(b/i<m) x+=(b/i);
else x+=m;
}
if(x>=k) e=b;
else s=b+1;
}
for(;s>0;s--){
for(int i=1;i<=n;i++){
if(s%i==0&&s/i<=m) return s;
}
}
}
};
解题思路:
首先看一下什么是Multiplication Table:https://en.wikipedia.org/wiki/Multiplication_table
我们可以清楚的看到第i行第j列的数等于i*j,根据这一点,可以很快的判断一个数x在n×m表中是第几大的:
第i行小于等于x的数有min(n,x/i)个,将m行的值加起来即可。
根据这一特点我们有了一个判断一个数x是在第k大的数之前还是之后的工具,有了这一工具,我们就可以使用二分法来获取第k大的数。
但获取到的数不一定在这个表里面,这时,找到表中比这个数小的最大的数即可。
复杂度为O(nlgk) n<=m;(第k大的数一定不大于k)。