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

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;
    }
}

相关文章:

  • 鸿蒙5.0实战案例:基于AVCodecKit的音视频解码及二次处理播放
  • 算法与数据结构(旋转链表)
  • 【每日八股】Redis篇(二):数据结构
  • Docker部署 MongoDB及常用命令
  • 定时任务特辑 Quartz、xxl-job、elastic-job、Cron四个定时任务框架对比,和Spring Boot集成实战
  • Linux7-线程
  • DDD - 整洁架构
  • vscode设置终端复制快捷键(有坑!!!)
  • 《论多源数据集成及应用》审题技巧 - 系统架构设计师
  • 大模型应用开发:核心技术与领域实践
  • Python常见面试题的详解19
  • WPF框架学习
  • maven模块化管理
  • openstack部署
  • pikachu靶场搭建教程
  • RocketMq学习笔记
  • 如何在idea中搭建SpringBoot项目
  • C++中结构体与结构体变量 和 类与对象的区别
  • Rust学习~tokio简介
  • 服务端渲染(SSR):概念、优势与实现
  • 我驻苏丹使馆建议在苏中国公民尽快撤离
  • 欧派家居:一季度营收降4.8%,目前海外业务整体体量仍较小
  • 国务院安委会办公室印发通知:坚决防范遏制重特大事故发生
  • 云南一男子酒后经常殴打七旬母亲,被警方拘14日罚600元
  • 李云泽:再批复600亿元,进一步扩大保险资金长期投资试点范围
  • 线下无理由退货怎样操作?线上线下监管有何不同?市场监管总局回应