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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,771評論 0 33
  • 緣起 原本認為Markdown是一種不合適我的東西,一方面需要記代碼,另一方面我更喜歡“所見即所得”的文本編輯,但...
    Fred_豐愷閱讀 567評論 0 0
  • 我與故鄉的搭訕 來自寂靜中的魂牽 許久脈脈的無言 想天地咫尺古今一覽 夜隨野陌流轉 我是天宇下的秋蠶 收...
    紀言閱讀 473評論 1 7
  • 幫我
    明璞新中式燈飾劉傳強閱讀 156評論 0 0