3.31 练手

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/vancooler/article/details/88926323

Leetcode 23题

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

解决方法:

使用最小堆解决

import heapq
class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        h = [] #minheap
        for listTemp in lists:
            while listTemp!=None:
                h.append(listTemp.val)                    #O(n)
                listTemp = listTemp.next
        heapq.heapify(h) # make h as a min heaq           O(n)
                         #this is an in-place function
       
        if len(h)==0:
            return []
        rootNote = ListNode(heapq.heappop(h))
        currentNote = rootNote
        while len(h)!=0: #h not empty
            currentNote.next = ListNode(heapq.heappop(h))
            currentNote = currentNote.next
            
        return rootNote

算上出堆调整时间复杂度为O(nlogn),想吐槽的地方是 while not h 一定要写成 while len(h)!=0 ,但是看stackoverflow上有人说可以这么写的。

猜你喜欢

转载自blog.csdn.net/vancooler/article/details/88926323