[leetcode] 668 Kth Smallest Number in Multiplication Table

本文介绍了一种高效的算法,用于找出给定乘法表中第K小的数字。通过分析乘法表的特点,利用二分搜索策略实现快速定位,并给出具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/description/

题目描述: Nearly every one have used the Multiplication Table. But could you find out the k-th smallest number quickly from the multiplication table?

Given the height m and the length n of a m * n Multiplication Table, and a positive integer k, you need to return the k-th smallest number in this table.

Example 1:

Input: m = 3, n = 3, k = 5
Output: 
Explanation: 
The Multiplication Table:
1   2   3
2   4   6
3   6   9

The 5-th smallest number is 3 (1, 2, 2, 3, 3).

我的代码:

class Solution {
public:
    int findKthNumber(int m, int n, int k) {
        if(m<n){
            int t=n;
            n=m;
            m=t;
        }
        int s=1,e=k;
        while(s!=e){
            int x=0;
            int b=(s+e)/2;
            for(int i=1;i<=n&&i<=b;i++){
                if(b/i<m) x+=(b/i);
                else x+=m;
            }
            if(x>=k) e=b;
            else s=b+1;
        }
        for(;s>0;s--){
            for(int i=1;i<=n;i++){
                if(s%i==0&&s/i<=m) return s;
            }   
        }
    }
};

解题思路:
首先看一下什么是Multiplication Table:https://en.wikipedia.org/wiki/Multiplication_table
我们可以清楚的看到第i行第j列的数等于i*j,根据这一点,可以很快的判断一个数x在n×m表中是第几大的:
第i行小于等于x的数有min(n,x/i)个,将m行的值加起来即可。
根据这一特点我们有了一个判断一个数x是在第k大的数之前还是之后的工具,有了这一工具,我们就可以使用二分法来获取第k大的数。
但获取到的数不一定在这个表里面,这时,找到表中比这个数小的最大的数即可。
复杂度为O(nlgk) n<=m;(第k大的数一定不大于k)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值