【发布时间】:2016-01-03 12:57:31
【问题描述】:
我最好用一个例子来解释
假设,我有一个列表 [6,3,5,1,4,2]。
从索引 0 开始,查找所有小于该索引值(未标记)的项目。
Index 0: [6,3,5,1,4,2]
Elements less than 6: 5{3,5,1,4,2}
Visited array: [1 0 0 0 0 0]
Index 1: [6,3,5,1,4,2]
Elements less than 3: 2 {1,2}
Visited array: [1 1 0 0 0 0]
Index 2: [6,3,5,1,4,2]
Elements less than 5: 3 {1,4,2}
Visited array: [1 1 1 0 0 0]
Index 3: [6,3,5,1,4,2]
Elements less than 1: 0 {NULL}
Visited array: [1 1 1 1 0 0]
Index 4: [6,3,5,1,4,2]
Elements less than 4: 1 {2}
Visited array: [1 1 1 1 1 0]
This yields an array as [5 2 3 0 1 0]
目前正在使用,
def get_diff(lis):
ans=[]
for index,elem in enumerate(lis):
number_of_smaller=len(filter(lambda x:x<elem ,lis[index+1:]))
ans.append(number_of_smaller)
return ans
但是,我感觉这不会有效。我如何使它值得一个巨大的清单?我闻到前缀和吗?谢谢,
【问题讨论】:
-
但是,我感觉这不会有效率。是什么让您有这种感觉?你测试了吗?
-
是的,长度为 10**4 的列表很容易嘲笑我的代码。当前的代码,虽然我认为 pythonic 不够快
-
你的算法复杂度为 O(n²)。如果你想让你的代码更快,你需要使用不同的算法。 (我有一个解决方案,但是这个边距太小,我写不出来。)
标签: python list sum python-2.x minimum