当前位置: 首页 > article >正文

Leetcode-668. Kth Smallest Number in Multiplication Table[C++][Java]

目录

一、题目描述

二、解题思路

【C++】

【Java】


Leetcode-668. Kth Smallest Number in Multiplication Tablehttps://leetcode.com/problems/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 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

二、解题思路

二分查找

  • 总时间复杂度为 O(m * log(m * n))
  • 空间复杂度为 O(1)

【C++】

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;
            int count = 0;
            for (int i = 1; i <= m; ++i) {
                count += min(mid / i, n);
            }
            if (count < k) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }
};

【Java】

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;
            int count = 0;
            for (int i = 1; i <= m; i++) {
                count += Math.min(mid / i, n);
            }
            if (count < k) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }
}


http://www.kler.cn/a/559481.html

相关文章:

  • 微信小程序页面导航与路由:实现多页面跳转与数据传递
  • 深入HBase——数据结构与算法
  • 计算机网络真题练习(高软29)
  • 一种简单的快速批量视频抽取固定间隔帧截图的操作方法
  • 【DevOps构筑篇】用SELinux强化Docker的安全性
  • DeepSeek模型量化
  • 常见的“锁”有哪些?
  • YOLOv12源码及模型权重——免费下载
  • 数据库增删查改sql语句
  • Laravel框架入门指南:从零开始构建现代Web应用
  • 输入框元素覆盖冲突
  • 计算机毕业设计SpringBoot+Vue.js教师工作量管理系统(源码+LW文档+PPT+讲解)
  • 编程小白冲Kaggle每日打卡(13)--kaggle学堂:<机器学习简介>基础数据探索
  • 基于javaweb的SpringBoot酒店管理系统设计和实现(源码+文档+部署讲解)
  • 【Python + STM32 实现外设控制的从0-1实例教程-适合新手】
  • JavaScript AJAX 库
  • day58 第十一章:图论part08
  • 大模型面试|大模型常考面经总结
  • Orange 单体架构 - 快速启动
  • 从零开始学 Rust:安装与 Hello World