One Leetcode per day-668. The k-th smallest number in the multiplication table [binary search]

Insert picture description here

class Solution(object):
    def findKthNumber(self, m, n, k):
        """
        :type m: int
        :type n: int
        :type k: int
        :rtype: int
        """
        # 乘法表中最小为1,最大为m*n
        l,r = 1, m*n
        while l<r:
            # >> 1 其实就是 除以2的操作
            mid = l+r >>1
            cnt = 0
            for i in range(1,m+1):
                # 逐行遍历
                # 计算每行小于等于mid的有多少数字
                # 每行都是:1*i,2*i,3*i,..t*i,..,n*i
                # t*i<=mid 则说明当前行有t个数字小于mid
                cnt += min(mid//i,n)
            if cnt<k:
                l = mid+1
            else:
                r = mid
        return l

Guess you like

Origin blog.csdn.net/weixin_41041275/article/details/112729589