# [LeetCode] 668. Kth Smallest Number in Multiplication Table 乘法表中的第K小的数字

Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed).

Given three integers mn, and k, return the kth smallest element in the m x n multiplication table.

Example 1:

Input: m = 3, n = 3, k = 5
Output: 3
Explanation: The 5th smallest number is 3.


Example 2:

Input: m = 2, n = 3, k = 6
Output: 6
Explanation: The 6th smallest number is 6.


Constraints:

• 1 <= m, n <= 3 * 104
• 1 <= k <= m * n

 class Solution {
public:
int findKthNumber(int m, int n, int k) {
int left = 1, right = m * n;
while (left < right) {
int mid = left + (right - left) / 2, cnt = 0;
for (int i = 1; i <= m; ++i) {
cnt += (mid > n * i) ? n : (mid / i);
}
if (cnt < k) left = mid + 1;
else right = mid;
}
return right;
}
};

 class Solution {
public:
int findKthNumber(int m, int n, int k) {
int left = 1, right = m * n;
while (left < right) {
int mid = left + (right - left) / 2, cnt = 0, i = m, j = 1;
while (i >= 1 && j <= n) {
if (i * j <= mid) {
cnt += i;
++j;
} else {
--i;
}
}
if (cnt < k) left = mid + 1;
else right = mid;
}
return right;
}
};

 class Solution {
public:
int findKthNumber(int m, int n, int k) {
int left = 1, right = m * n;
while (left < right) {
int mid = left + (right - left) / 2, cnt = 0, i = m, j = 1;
while (i >= 1 && j <= n) {
int t = j;
j = (mid > n * i) ? n + 1 : (mid / i + 1);
cnt += (j - t) * i;
i = mid / j;
}
if (cnt < k) left = mid + 1;
else right = mid;
}
return right;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/668

Kth Smallest Element in a Sorted Matrix

Find K-th Smallest Pair Distance

https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/

https://discuss.leetcode.com/topic/101194/my-8-lines-c-solution

https://discuss.leetcode.com/topic/101132/java-solution-binary-search

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2018-01-27 22:38  Grandyang  阅读(4952)  评论(7编辑  收藏  举报