668. Kth Smallest Number in Multiplication Table

Description

image-20211121232323235

image-20211121232334372

Solution

Generally, k-th related problem could be solved by binary search to guess the right answer and verify. Once we enumerate a number, we could calculate its rank.

Another important thing we should notice is that we calculate the elements number that less equal than the target one.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int findKthNumber(int m, int n, int k) {
int l = 1, r = m * n;
while(l < r){
int mid = l + (r - l)/2;
//Analyze mid's property, factorization
if(count_le(mid, m, n) < k){
l = mid + 1;
}else{
r = mid;
}
}
return l;
}

int count_le(int val, int m, int n){
int cnt = 0;
for(int i = 1; i <= m; i++){
cnt += min(n, val / i);
}
return cnt;
}
};