
Sponsored
Sponsored
The general idea is to use binary search to find the kth smallest element in the multiplication table. The key observation is that for a candidate number X, we can count how many numbers in the multiplication table are less than or equal to X, without constructing the entire table explicitly. Counting these numbers can be efficiently done by iterating over the rows and determining the highest multiple that does not exceed X.
Time Complexity: O(m * log(m * n))
Space Complexity: O(1)
1class Solution {
2 public int countLessOrEqual(int m, int n, int x) {
3 int count = 0;
4 for (int i = 1; i <= m; i++) {
5 count += Math.min(x / i, n);
6 }
7 return count;
8 }
9
10 public int findKthNumber(int m, int n, int k) {
11 int low = 1, high = m * n;
12 while (low < high) {
13 int mid = low + (high - low) / 2;
14 if (countLessOrEqual(m, n, mid) < k)
15 low = mid + 1;
16 else
17 high = mid;
18 }
19 return low;
20 }
21
22 public static void main(String[] args) {
23 Solution sol = new Solution();
24 System.out.println(sol.findKthNumber(3, 3, 5)); // Output: 3
25 }
26}This Java solution applies binary search to find the kth smallest number in a multiplication table. The main idea is to count how many multiples are below a mid-point of the binary search range and narrow it based on k.
This approach uses a min-heap (priority queue) to keep track of the smallest unseen elements in the multiplication table. By continuously adding the next minimum elements from the rows, we can extract them in order until we reach the kth smallest element.
Time Complexity: O(k log m)
Space Complexity: O(m)
1#include <iostream>
2#include <queue>
3#include <vector>
4
5struct Comparator {
6 bool operator()(std::pair<int, int> &a, std::pair<int, int> &b) {
return a.first > b.first;
}
};
int findKthNumber(int m, int n, int k) {
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, Comparator> minHeap;
for (int i = 1; i <= m; ++i)
minHeap.push({i, 1});
int count = 0, ans = 0;
while (!minHeap.empty() && count < k) {
auto elem = minHeap.top();
minHeap.pop();
++count;
ans = elem.first;
if (elem.second < n) {
minHeap.push({elem.first + elem.first / elem.second, elem.second + 1});
}
}
return ans;
}
int main() {
int m = 3, n = 3, k = 5;
std::cout << findKthNumber(m, n, k) << std::endl; // Output: 3
return 0;
}This C++ code uses a min-heap to track the smallest values efficiently. We insert initial multiples from each row into the heap and extract the smallest at each step, pushing the next element from the same row.