Given an integer n
, return all the numbers in the range [1, n]
sorted in lexicographical order.
You must write an algorithm that runs in O(n)
time and uses O(1)
extra space.
Example 1:
Input: n = 13 Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
Example 2:
Input: n = 2 Output: [1,2]
Constraints:
1 <= n <= 5 * 104
这题看起来不太像可以用前缀树(Trie)来解答,但题目的关键字“字典序lexicographical“”却是前缀树的一个特性,前缀树从根顶点开始从上到下从左到右刚好是按字典序排序的。
解题思路:
把从1到n的数转化成字符串,用标准的前缀树插入函数把数字字符串按字符插入前缀树里,另外在每个节点把对应的数字存下来方便后面遍历时读取。
从上到下从左到右遍历整棵前缀树,把遇到的每个节点的数字取出放入答案中。
class TrieNode:
def __init__(self):
self.num = 0
self.children = [None] * 10
class Solution:
def lexicalOrder(self, n: int) -> List[int]:
root = TrieNode()
for i in range(1,n + 1):
self.insert(root, i)
res = []
self.search(root, res)
return res
def insert(self, root, i):
s = str(i)
node = root
for c in s:
idx = int(c)
if not node.children[idx]:
node.children[idx] = TrieNode()
node = node.children[idx]
node.num = i
def search(self, root, ans):
if root.num > 0:
ans.append(root.num)
for i in range(10):
if not root.children[i]:
continue
self.search(root.children[i], ans)
注:这题要求空间复杂度为O(1),很显然用了前缀树就到不到满足要求,但也不失为一题好的前缀树Trie练习题。