Merging two sorted lists into one in descending order

和自甴很熟 提交于 2019-12-23 18:53:39

问题


I've been able to figure out how to merge two sorted lists in ascending order, but I'm having trouble finding a way to do so in the opposite direction. How can I merge the two lists into one in descending order without reversing the string after?


回答1:


You just have to do everything in the opposite way--retrieve items from the tail instead of the head, go for the larger of the two when making comparisons, and return the remaining list in reverse order when the other is exhausted:

def merge(lst1, lst2):
    if not lst1:
        return lst2[::-1]
    if not lst2:
        return lst1[::-1]
    if lst1[-1] < lst2[-1]:
        return [lst2[-1]] + merge(lst1, lst2[:-1])
    else:
        return [lst1[-1]] + merge(lst1[:-1], lst2)

so that:

 merge([2,5,9,12], [0,1,3,4,8])

would return:

 [12, 9, 8, 5, 4, 3, 2, 1, 0]


来源:https://stackoverflow.com/questions/52528449/merging-two-sorted-lists-into-one-in-descending-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!