lintcode练习-104. Merge K Sorted Lists

描述

合并k个排序链表,并且返回合并后的排序链表。尝试分析和描述其复杂度。

您在真实的面试中是否遇到过这个题?  是

样例

给出3个排序链表[2->4->null,null,-1->null],返回 -1->2->4->null

解题思路:

顾名思义,这个最好的解法是使用归并排序,还有一种方法是堆排序。

mergesort:

#归并排序的思想
"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""


class Solution:
    """
    @param lists: a list of ListNode
    @return: The head of one sorted list.
    """

    def mergeKLists(self, lists):
        # write your code here
        # 定义一个列表保存最小的链表
        if len(lists) < 1:
            return None

        return self.helper(lists, 0, len(lists) - 1)

    def helper(self, lists, start, end):
        if start == end:
            return lists[start]

        mid = start + (end - start) // 2
        left = self.helper(lists, start, mid)
        right = self.helper(lists, mid + 1, end)

        return self.mergeTwoList(left, right)

    def mergeTwoList(self, list1, list2):
        dummy = tial = ListNode(None)

        while list1 and list2:
            if list1.val < list2.val:
                tial.next = list1
                tial = tial.next
                list1 = list1.next
            else:
                tial.next = list2
                tial = tial.next
                list2 = list2.next

        if list1:
            tial.next = list1
        else:
            tial.next = list2

        return dummy.next

heapsort:

#堆排序
from heapq import heappop, heappush

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""


class Solution:
    """
    @param lists: a list of ListNode
    @return: The head of one sorted list.
    """

    def mergeKLists(self, lists):
        # write your code here
        # 定义一个列表保存最小的链表
        if lists == []:
            return None
        if len(lists) == 1:
            return lists[0]

        heap = []
        for node in lists:
            # if node:
            #     heappush(heap, (node.val, node))
            while node:
                heappush(heap, node.val)
                node = node.next

        dummy = tial = ListNode(None)
        while heap:
            tial.next = ListNode(heappop(heap))
            tial = tial.next
        return dummy.next

mergesort
时间复杂度:nlgk 空间复杂度:1
heapsort:
时间复杂度:n
lgn(建堆复杂度n但是排序是nlgn)
空间复杂度:n
暴力:n
lgn

mergesort肯定其他两个方法好 因为lgk < lgn
这题要考察的肯定是merge sort
可以先用暴力和heap让面试官了解一下你的知识面

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81194301