您好,欢迎来到年旅网。
搜索
您的当前位置:首页LeetCode: 668. 乘法表中第k小的数

LeetCode: 668. 乘法表中第k小的数

来源:年旅网

题目

几乎每一个人都用 乘法表。但是你能在乘法表中快速找到第k小的数字吗?

给定高度m 、宽度n 的一张 m * n的乘法表,以及正整数k,你需要返回表中第k 小的数字。

官方样例

自测样例

题解思路(自测样例为数据)

AC代码·暴力版

class Solution {
    public int findKthNumber(int m, int n, int k) {
        int left = 1;
        int right = m * n;

        while (left < right) {
            int x = (left + right) / 2;
            int count = 0;
            for (int i = 1; i <= m; i++) {
                count += Math.min(x / i,n);
            }
            if(count >= k){
                right = x;
            } else {
                left = x + 1;
            }
        }
        return left;
    }
}

AC代码·精益求精版

class Solution {
    public int findKthNumber(int m, int n, int k) {
        int left = 1;
        int right = m * n;

        while (left < right) {
            int x = (left + right) / 2;
            int count = (x / n) * n;
            for (int i = x / n + 1; i <= m; i++) {
                count += x / i;
            }
            if(count >= k){
                right = x;
            } else {
                left = x + 1;
            }
        }
        return left;
    }
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务