链接:LeetCode668
给定高度m 、宽度n 的一张 m * n的乘法表,以及正整数k,你需要返回表中第k 小的数字。
例 1:
输入: m = 3, n = 3, k = 5
输出: 3
解释:
乘法表:
1 2 3
2 4 6
3 6 9
第5小的数字是 3 (1, 2, 2, 3, 3).
相关标签:二分查找
乘法表的特点是每行和每列元素均按升序排序,这题就可以转换为[LeetCode]378.Kth Smallest Element in a Sorted Matrix。我们通过二分查找不断逼近真实值即可。
代码如下:
python:
class Solution:
def findKthNumber(self, m: int, n: int, k: int) -> int:
lo, hi = 1, m*n
while lo <= hi:
mid = (lo + hi) >> 1
loc = self.countLower(m,n, mid)
if loc < k:
lo = mid + 1
else:
hi = mid - 1
return lo
def countLower(self, m,n, num):
i, j = 1,n
cnt = 0
while i <= m and j >= 1:
if i*j <= num:
cnt += j
i += 1
else:
j -= 1
return cnt
C++:
class Solution {
public:
int findKthNumber(int m, int n, int k) {
int lo=1,hi=m*n;
while(lo<=hi){
mid = lo+((hi-lo)>>1);
cnt = countSamller(m,n,mid);
if(k <= cnt){
hi = mid-1;
} else {
lo = mid+1;
}
}
return lo;
}
int countSamller(int m,int n,int target){
int i=1,j=n;
int cnt = 0;
while(i<=m && j>=1){
if(target<(i*j)){
j--;
}else{
cnt += j;
i++;
}
}
return cnt;
}
};