1.给定两个有序列表,l1=[1,5,7,10],l2=[2,3,4,11],把他们合并成一个有序列表
2.方法一:
def merge_sort(l1,l2):
i,j = 0,0
result = []
while i < len(l1) and j <len(l2):
if l1[i]< l2[j]:
result.append(l1[i])
i += 1
else:
result.append(l2[j])
j += 1
result += l1[i:]
result += l2[j:]
return result
print(merge_sort(l1,l2))
结果:
[1, 2, 3, 4, 5, 7, 10, 11]
3.方法二:
import heapq
l1 = [1,5,7,10]
l2 = [2,3,4,11]
l3 = []
for i in heapq.merge(l1,l2):
print(i)
结果:
1
2
3
4
5
7
10
11