[英]merge two sorted list of items in python
我的问题与找出合并 2 个已排序项目的不同方法有关? 我试图找到一种简单的方法来合并 2 个已排序的项目。
def merge(arr1, arr2):
return sorted(arr1 + arr2)
# Example: merge([1, 4, 7], [2, 3, 6, 9]) => [1, 2, 3, 4, 6, 7, 9]
我不确定我是否把它复杂化了。 这使用了一个内置函数,这意味着更难弄乱实现细节。
我还发现我可以使用来自cypthon 的 heapq的 merge() 函数。
想知道是否有使用其他方法的想法如下:
使用来自 heapq 的合并
>>> l1 = [1, 4, 7]
>>> l2 = [2, 3, 6, 9]
>>> from heapq import merge
>>> list(merge(l1,l2))
[1, 2, 3, 4, 6, 7, 9]
取决于您使用哪种实现。 需要考虑的是您是需要干净的代码还是需要性能。
对于干净的代码,您可以使用:
这两者的复杂度都是 O(nlogn)
而这个实现是https://gist.github.com/Jeffchiucp/9dc2a5108429c4222fe4b2a25e35c778 ,算法复杂度为 O(n)。
您不想连接两个已排序的列表并再次对其进行排序,这是不需要的。 有用于合并排序列表的O(n)
算法,由于再次排序,您的算法将是O(n log n)
。 使用从此处获取的Priority queue
合并两个排序列表:
from Queue import PriorityQueue
class Solution(object):
def mergeKLists(self, lists):
dummy = ListNode(None)
curr = dummy
q = PriorityQueue()
for node in lists:
if node: q.put((node.val,node))
while q.qsize()>0:
curr.next = q.get()[1]
curr=curr.next
if curr.next: q.put((curr.next.val, curr.next))
return dummy.next
这是我的解决方案:
def merge_sorted_list(list1,list2):
i = j = 0
while(i < len(list1) and j < len(list2)):
if(list1[i] > list2[j]):
list1.insert(i, list2[j])
i+=1
j+=1
else:
i+=1
if(j < len(list2)):
list1.extend(list2[j:])
return list1
print(merge_sorted_list([1, 4, 7],[2, 3, 6, 9]))
def cleanMerge(self, list1, list2):
if len(list1)!=len(list2):
less = list1 if len(list1)<len(list2) else list2
chosenList = list2 if len(list1)<len(list2) else list1
chosenList = list1
less = list2
l1,l2,r1,r2 = 0,0,len(chosenList),len(less)
while l2<r2 and l1<r1:
if chosenList[l1]>less[l2]:
chosenList[l1+1:r1+1] = chosenList[l1:r1]
chosenList[l1] = less[l2]
l2+=1
l1+=1
r1+=1
else:
l1+=1
continue
if l2<r2:
for item in less[l2:r2]:
chosenList.append(item)
return chosenList
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.