【Leetcode】668. Kth Smallest Number in Multiplication Table

题目地址:

https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/

给定一个 m × n m\times n m×n的乘法表,找到第 k k k小的数。

思路是二分答案。答案的区间是 [ 1 , m n ] [1,mn] [1,mn],二分出 s s s后,算一下比 s s s小于等于的数有多少个,这可以从左下角 ( x , y ) = ( m , n ) (x,y)=(m,n) (x,y)=(m,n)出发,如果遇到比 s s s小于等于的数,则计数累加 x x x并右移,否则上移。累加完之后看一下小于等于 s s s的数的个数与 k k k之比较,如果大于等于 k k k则说明最终答案不大于 s s s,则收缩右边界到 s s s,否则收缩左边界到 s + 1 s+1 s+1。代码如下:

public class Solution {
    
    
    public int findKthNumber(int m, int n, int k) {
    
    
        int l = 1, r = m * n;
        while (l < r) {
    
    
            int mid = l + (r - l >> 1);
            int x = m, y = 1, count = 0;
            while (x >= 1 && y <= n) {
    
    
                if (x * y <= mid) {
    
    
                    count += x;
                    y++;
                } else {
    
    
                    x--;
                }
            }
            
            if (count >= k) {
    
    
                r = mid;
            } else {
    
    
                l = mid + 1;
            }
        }
        
        return l;
    }
}

时间复杂度 O ( ( m + n ) log ⁡ ( m n − 1 ) ) O((m+n)\log (mn-1)) O((m+n)log(mn1)),空间 O ( 1 ) O(1) O(1)

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/113065814