8.22 - hard - 85

440. K-th Smallest in Lexicographical Order

和之前有一道386. Lexicographical Numbers 很像。不过直接套用的话会TLE。利用可能解区间的长度来快速衰减K有点log的解法

TLE版本
class Solution(object):
    def findKthNumber(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: int
        """
        res = [1]
        while len(res) < n:
            new = res[-1] * 10
            while new > n:
                new /= 10
                new += 1
                while new % 10 == 0:
                    new /= 10
            res.append(new)
        return res[k-1]
class Solution(object):
    def findKthNumber(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: int
        """
        result = 1;
        k -= 1
        while k > 0:
            count = 0
            interval = [result, result+1]
            while interval[0] <= n:
                count += (min(n+1, interval[1]) - interval[0])
                interval = [10*interval[0], 10*interval[1]]
            
            if k >= count:
                result += 1
                k -= count
            else:
                result *= 10
                k -= 1
        return result
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,890评论 0 33
  • 缘起 原本认为Markdown是一种不合适我的东西,一方面需要记代码,另一方面我更喜欢“所见即所得”的文本编辑,但...
    Fred_丰恺阅读 613评论 0 0
  • 我与故乡的搭讪 来自寂静中的魂牵 许久脉脉的无言 想天地咫尺古今一览 夜随野陌流转 我是天宇下的秋蚕 收...
    纪言阅读 497评论 1 7
  • 帮我
    明璞新中式灯饰刘传强阅读 170评论 0 0

友情链接更多精彩内容