美文网首页
8.22 - hard - 85

8.22 - hard - 85

作者: 健时总向乱中忙 | 来源:发表于2017-08-23 02:27 被阅读0次

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

相关文章

  • 8.22 - hard - 85

    440. K-th Smallest in Lexicographical Order 和之前有一道386. Le...

  • 8.22 - hard - 86

    446. Arithmetic Slices II - Subsequence 一道dp的题目

  • 8.22 - hard - 87

    460. LFU Cache 有点做不动了。。。基本思想是。。。(这题要重看,先休息一会)

  • 8.22 - hard - 90

    471. Encode String with Shortest Length 一道对角线型dp题目,对角线是我自...

  • 8.22 - hard - 88

    465. Optimal Account Balancing 这道题挺有意思的,用greedy的方法

  • 8.22 - hard - 89

    466. Count The Repetitions这题好困难,看了答案也很难理解,估计只能背答案了。。。等复习的...

  • 8.22 - hard - 81

    411. Minimum Unique Word Abbreviation 利用比较基本的方法,backtrack...

  • 8.22 - hard - 83

    425. Word Squares 利用Trie和backtracking来做。利用trie来找prefix

  • 8.22 - hard - 84

    432. All O`one Data Structure 基本的想法就是利用一个双向链表来维持单调性,每个nod...

  • 8.22 - hard - 82

    420. Strong Password Checker 这道题要分成几种情况做When len > 20, we...

网友评论

      本文标题:8.22 - hard - 85

      本文链接:https://www.haomeiwen.com/subject/wdwrdxtx.html