23. 合并多个排序链表:https://leetcode-cn.com/problems/merge-k-sorted-lists/
这道题其实比较简单,关键是掌握堆和分治法, 写分治法的时候,涉及到递归,这块是我的一个弱项,一开始没写出来,分治法模板可以参考一下:
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
return self.helper(0, len(lists), lists)
# 分治法合并
def helper(self, start, end, lists):
if start == end:
return lists[start]
mid = start + (end - start) / 2
left = self.helper(start, mid, lists)
right = self.helper(mid+1, end, lists)
return self.mergeTwoSortLists(left, right)
def mergeTwoSortLists(self, list1, list2):
'''
@description: 合并两个排序链表
@param {type}
list1: <ListNode>
list2: <ListNode>
@return:
result: <ListNode, 排序好的合并链表>
@author: zhangzhen20
'''
dummy = listNode(-1)
cur = dummy
while list1 and list2:
if list1.val < list2.val:
cur.next = list1
list1 = list1.next
else:
cur.next = list2
list2 = list2.next
if list1 is None:
cur.next = list2
else:
cur.next = list1
return dummy.next
网友评论