668. Kth Smallest Number in Multiplication Table

本文介绍了一种使用二分搜索算法解决寻找m*n乘法表中第K小元素的问题的方法。通过设定搜索范围从1到m*n,并不断调整中间值来缩小搜索范围,最终找到目标元素。

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

1. Description

Given three elements m, n and k. Find the k-th smallest number in the m*n Multiplication Table.


2. Solution

Binary Search.

The left point is 1, and the right point is m*n.

While left is smaller than right,

find the middle of left and right, and then calculate the number of elements not bigger than the middle value.

If the number is smaller than k, then set left to middle+1;

otherwise, set right to middle.

Return the final left point.


3. Code

    int findKthNumber(int m, int n, int k) {
        int l = 1, r=m*n;
        while(l<r){
            int mid = l+(r-l)/2;
            int cnt = count(mid,m,n);
            if(k<=cnt)
                r=mid;
            else
                l=mid+1;
        }
        return r;
    }
    int count(int mid,int m,int n){
        int cnt = 0;
        for(int i=1;i<=m;i++){
            cnt+=min(mid/i,n);
        }
        return cnt;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值