返回介绍

solution / 0600-0699 / 0668.Kth Smallest Number in Multiplication Table / README_EN

发布于 2024-06-17 01:03:35 字数 3511 浏览 0 评论 0 收藏 0

668. Kth Smallest Number in Multiplication Table

中文文档

Description

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 m, n, 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

Solutions

Solution 1

class Solution:
  def findKthNumber(self, m: int, n: int, k: int) -> int:
    left, right = 1, m * n
    while left < right:
      mid = (left + right) >> 1
      cnt = 0
      for i in range(1, m + 1):
        cnt += min(mid // i, n)
      if cnt >= k:
        right = mid
      else:
        left = mid + 1
    return left
class Solution {
  public int findKthNumber(int m, int n, int k) {
    int left = 1, right = m * n;
    while (left < right) {
      int mid = (left + right) >>> 1;
      int cnt = 0;
      for (int i = 1; i <= m; ++i) {
        cnt += Math.min(mid / i, n);
      }
      if (cnt >= k) {
        right = mid;
      } else {
        left = mid + 1;
      }
    }
    return left;
  }
}
class Solution {
public:
  int findKthNumber(int m, int n, int k) {
    int left = 1, right = m * n;
    while (left < right) {
      int mid = (left + right) >> 1;
      int cnt = 0;
      for (int i = 1; i <= m; ++i) cnt += min(mid / i, n);
      if (cnt >= k)
        right = mid;
      else
        left = mid + 1;
    }
    return left;
  }
};
func findKthNumber(m int, n int, k int) int {
  left, right := 1, m*n
  for left < right {
    mid := (left + right) >> 1
    cnt := 0
    for i := 1; i <= m; i++ {
      cnt += min(mid/i, n)
    }
    if cnt >= k {
      right = mid
    } else {
      left = mid + 1
    }
  }
  return left
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文