1. Description
Given three elements m, n and k. Find the k-th smallest number in the m*n Multiplication Table.
2. Solution
Binary Search.
The left point is 1, and the right point is m*n.
While left is smaller than right,
find the middle of left and right, and then calculate the number of elements not bigger than the middle value.
If the number is smaller than k, then set left to middle+1;
otherwise, set right to middle.
Return the final left point.
3. Code
int findKthNumber(int m, int n, int k) {
int l = 1, r=m*n;
while(l<r){
int mid = l+(r-l)/2;
int cnt = count(mid,m,n);
if(k<=cnt)
r=mid;
else
l=mid+1;
}
return r;
}
int count(int mid,int m,int n){
int cnt = 0;
for(int i=1;i<=m;i++){
cnt+=min(mid/i,n);
}
return cnt;
}