什么是O(n)的算法配对两个同样lengthed列表,以到位? [英] What is an O(n) algorithm to pair two equally lengthed lists in order in place?
本文介绍了什么是O(n)的算法配对两个同样lengthed列表,以到位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假如我有在Python两条等长的无序列表:
A = [5,2,3,1,4]
B = ['D','B','A','C','E']
是否有一个O(N),原地算法,得到如下结果?
[(1,'A'),(2,'B'),(3,'C'),(4,'D'),(5,'E ')]
小于或等于N.
解决方案
是的,有一种方法可以得到O(N)排序时正整数 做到这一点的方法是使用桶。 下面是一个实现:
高清_sort(_list):
水桶= [0] * len个(_list)
因为我在_list:
I = INT(I)
断言(0℃= I< LEN(_list))
水桶[I] + = 1
结果= []
为NUM,算上历数(桶):
result.extend([数字] *计)
返回结果
ALP =地图(ORD,列表(dabce))
M =分钟(ALP)
高山= [I-M为我在高山]
ALP = _sort(ALP)
高山= [我在高山+ M的我]
ALP =图(CHR,ALP)
打印拉链(_sort([1,3,2,0,4]),ALP)
#[(0,'一'),(1,'B'),(2,'C'),(3,'D'),(4,'E')]
Suppose I have two unordered lists of equal length in Python:
a = [5, 2, 3, 1, 4]
b = ['d', 'b', 'a', 'c', 'e']
Is there an O(n), in-place algorithm to obtain the following result?
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
解决方案
Yes there is a way to get O(N) when sorting positive integers less than or equal to N. The way to do it is to use buckets. Here is an implementation:
def _sort(_list):
buckets=[0]*len(_list)
for i in _list:
i=int(i)
assert(0<=i<len(_list))
buckets[i]+=1
result=[]
for num,count in enumerate(buckets):
result.extend([num]*count)
return result
alp=map(ord,list("dabce"))
m=min(alp)
alp=[i-m for i in alp]
alp=_sort(alp)
alp=[i+m for i in alp]
alp=map(chr,alp)
print zip(_sort([1,3,2,0,4]),alp)
#[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]
这篇关于什么是O(n)的算法配对两个同样lengthed列表,以到位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文