標籤(空格分隔): LeetCodepython
做者: 負雪明燭
id: fuxuemingzhu
我的博客: http://fuxuemingzhu.me/app
題目地址:https://leetcode.com/problems/lexicographical-numbers/description/less
Given an integer n, return 1 - n in lexicographical order.ide
For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].spa
Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.code
給了一個數字n,找出1~n的全部數字的字典序排列。隊列
題目中說了輸入多是5百萬,那麼只能用O(N)的時間複雜度。ip
這個題的思路我是參考的Lexicographical Numbers 字典順序的數字,不太好想。leetcode
好比n=300
時,會有這個隊列1,10,100,101,102...198,199,2,20,200,201...299,3,30,300
get
代碼以下:
class Solution: def lexicalOrder(self, n): """ :type n: int :rtype: List[int] """ cur = 1 ans = [] for i in range(n): ans.append(cur) if cur * 10 <= n: cur *= 10 else: if cur >= n: cur //= 10 cur += 1 while cur % 10 == 0: cur //= 10 return ans
2018 年 8 月 17 日 ———— 別人七夕,我在刷題。。