当前位置: 首页 > 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):概念、优势与实现
  • 举牌超200轮!中铁建7.76亿元竞得北京通州梨园宅地
  • 中方发布《不跪!》视频传递何种信息?外交部回应
  • 一位排球青训教练的20年时光:努力提高女排球员成才率
  • 在循环往复的拍摄中,重新发现世界
  • 日韩 “打头阵”与美国贸易谈判,汽车、半导体产业忧虑重重
  • 上海乐高乐园建设进入最后冲刺,开园限量纪念年卡将于5月开售