leetcode 每日一题 23. 合并K个排序链表
分治法
思路:
先设计好两个链表的有序合并,然后采用分治,每次合并两个链表,知道最后得到结果
代码1:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeKLists(self, lists): length = len(lists) if length == 0: return None interval = 1 while interval < length: for i in range(0, length - interval, interval * 2): lists[i] = self.merge2Lists(lists[i], lists[i + interval]) interval *= 2 return lists[0] def merge2Lists(self, l1, l2): head = ListNode(-1) temp = head while l1 and l2: if l1.val <= l2.val: temp.next = l1 l1 = l1.next else: temp.next = l2 l2 = l2.next temp = temp.next temp.next = l1 if l1 else l2 return head.next
代码2:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeKLists(self, lists): length = len(lists) if length == 0: return None return self.merge(lists,0,len(lists)-1) def merge(self,lists, left, right): if left == right: return lists[left] mid = left + (right - left) // 2 l1 = self.merge(lists, left, mid) l2 = self.merge(lists, mid+1, right) return self.merge2Lists(l1, l2) def merge2Lists(self, l1, l2): head = ListNode(-1) temp = head while l1 and l2: if l1.val <= l2.val: temp.next = l1 l1 = l1.next else: temp.next = l2 l2 = l2.next temp = temp.next temp.next = l1 if l1 else l2 return head.next