手撕字典序数组还原成正常排序, 要求ON时间复杂度
1
11
111
2
...
9
注释就不写了,常规的建树+树的层序遍历,dddd(懂的都懂)
发现了一个编码更快的方法:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : qichun tang
# @Date : 2021-08-29
# @Contact : qichun.tang@bupt.edu.cn
import numpy as np
np.random.seed(0)
str_num = np.random.choice([str(i) for i in range(1, 1000)], 500)
str_num.sort()
print('字典序:')
print(str_num)
class Node:
node_map = {}
def __init__(self, value='', exist=True):
self.value = value
self.exist = exist
self.parent = None
self.children = []
if value:
pv = value[:-1]
if pv in Node.node_map:
self.parent = Node.node_map[pv]
else:
self.parent = Node(pv, False)
self.parent.children.append(self)
Node.node_map[value] = self
def __str__(self):
return f"Node({self.value}, {self.exist})"
__repr__ = __str__
for num in str_num:
Node(num)
queue = [Node.node_map['']]
ret = []
while queue:
top = queue.pop(0)
if top.exist:
ret.append(top.value)
for child in top.children:
queue.append(child)
print('普通序:')
print(ret)