标签(空格分隔): 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 日 ———— 别人七夕,我在刷题。。