python leetcode 440. K-th Smallest in Lexicographical Order

如果按照Lexicographical Numbers这道题进行遍历取值显然会超时(n最大可能为10^9 也就是说必须要用30位bit存 30*10^9 数据量是非常大的)
先来看看n=100 1,10,100,11,12,13,14,15,16,17,18,19,2… 1下面对应10,11,…,19, 10下面对100这样就对应于一个10叉树 类似先序遍历顺序即为序号
cur先为1 要快速定位到第K小所在的位置
譬如1到2中间隔了多少数字step=1+10+1

  • first=1 last=2
  • step+=1
  • first=10 last=20
  • step+=10
  • first=100 last=200
  • step=101-100 因为last>100
    然后判断k是否在1到2的步数中
  • 如果在 则cur=10*cur k-=1
  • 如果不在 cur=cur+1 k-=step

在这里插入图片描述

class Solution(object):
    def findKthNumber(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: int
        """
        cur=1
        k-=1
        while k>0:
            step,first,last=0,cur,cur+1
            while first<=n:
                step+=min(last,n+1)-first
                first*=10
                last*=10
            if k>=step:
                k-=step
                cur+=1
            else:
                cur*=10
                k-=1 
        return cur

猜你喜欢

转载自blog.csdn.net/Neekity/article/details/84704272
今日推荐