668. 乘法表中第k小的数

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-smallest-number-in-multiplication-table
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


本题和378. 有序矩阵中第 K 小的元素逻辑是一样的。

    public int findKthNumber(int m, int n, int k) {

        int l = 1;
        int r = m*n;
        while(l<r) {
            int mid = l+(r-l)/2;
            if(find(m,n,mid) < k) {
                l = mid+1; 
            }else {
                r= mid;
            }
        }
        return l;

    }

    public int find(int m, int n, int target) {
        int count = 0;

        for(int i=1;i<=n;i++) {
            while(m*i > target) {
                m--;
                if(m==0) {
                    return count;
                }
            }
            count+=m;
        }
        return count;
    }
posted @ 2022-03-03 15:45  一颗青菜  阅读(7)  评论(0)    收藏  举报