嘿, 一個解決方案,我想了解一點關於Python,所以我決定效仿谷歌的tutorial。無論如何,我有一個問題關於他們的一個解決方案的練習。問題從谷歌的Python類日
我是這樣做的。
# E. Given two lists sorted in increasing order, create and return a merged
# list of all the elements in sorted order. You may modify the passed in lists.
# Ideally, the solution should work in "linear" time, making a single
# pass of both lists.
def linear_merge(list1, list2):
# +++your code here+++
return sorted(list1 + list2)
然而他們以更復雜的方式做到了。 Google的解決方案是否更快?因爲我在註釋行中注意到解決方案應該在「線性」時間內工作,而我的解決方案可能不是?
這是他們的溶液
def linear_merge(list1, list2):
# +++your code here+++
# LAB(begin solution)
result = []
# Look at the two lists so long as both are non-empty.
# Take whichever element [0] is smaller.
while len(list1) and len(list2):
if list1[0] < list2[0]:
result.append(list1.pop(0))
else:
result.append(list2.pop(0))
# Now tack on what's left
result.extend(list1)
result.extend(list2)
return result
「從列表中彈出需要移動所有以後的項目」。這實際上取決於底層的列表實現。無論通過鏈表或數組完成實現,彈出第一個元素都可以很容易地在O(1)中實現。 – 2011-04-30 12:03:20
@IoanAlexandruCucu:當然這取決於底層的列表實現,但我們正在討論具體的實現:Python。什麼實現與我描述的不同? – 2011-04-30 12:09:41
這個解決方案也是O(nlogn),基本上只是'sorted(list1 + list2) '的一個非常複雜的版本。不要像你那樣混合推送和彈出,你也可以將堆中的所有項目一次推送到堆上。這在時間複雜度方面沒有什麼區別,用於構建堆的是'O(nlogn)'。確實,'list.pop(0)'不需要一定的時間,但是有一個數據結構:'collections.deque'。只需將'list1,list2 = deque(list1),deque(list2)'添加到google解決方案的頂部,就可以真正實現linerar。 – 2011-04-30 13:20:30