[leetcode] 23. Merge k Sorted Lists

时间:2021-12-10 19:48:27

[leetcode] 23. Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

题意:给定k条有序列表,合并成一条有序列表

题解:将k条列表看成是归并排序时分开的k个列表,利用两两合并的方法(自己实现的合并两条有序列表)将k的列表合并

代码(python实现):

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
    def mergeKLists(self, lists):
        """ :type lists: List[ListNode] :rtype: ListNode """
        l = len(lists)
        h = 2
        k = 1
        if lists:     
            i = 0
            while k < l:
                for i in range(0, l, h):
                    if i + k < l:
                       lists[i] = self.merge2Lists(lists[i], lists[i+k])
                h *= 2
                k *= 2
            return lists[0]
        return lists

    def merge2Lists(self, l1, l2):
        head = point = ListNode(0)
        while l1 and l2:
            if l1.val <= l2.val:
                point.next = l1
                l1 = l1.next
            else:
                point.next = l2
                l2 = l1
                l1 = point.next.next
            point = point.next
        if not l1:
            point.next=l2
        else:
            point.next=l1
        return head.next

附上AC情况:

[leetcode] 23. Merge k Sorted Lists