每日一道算法題--leetcode 23--合併k個排序鏈表--python

【題目描述】bash

【思路解析】

採用分治,兩兩合併,直至只有一個鏈表爲止。從8個鏈表變成4,再變成2,最後獲得一個鏈表。app

【源代碼】優化

時間複雜度爲O(Nlogk),k爲總鏈表個數,N爲鏈表總節點數。ui

空間複雜度爲k/2+k/4+...+1,等比數列求和等於O(k)。spa

空間複雜度還能夠進一步優化爲O(1),能夠參考這個見方法5code

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        if len(lists)==0:
            return None
        if len(lists)==1:
            return lists[0]
        left=0
        right=len(lists)-1
        newlist=[]
        while left<right:
            newlist.append(self.merge2link(lists[left],lists[right]))
            left+=1
            right-=1
        if left==right:
            newlist.append(lists[left])
        return self.mergeKLists(newlist)   
    def merge2link(self,head1,head2):
        if head1!=None and head2!=None:
            if head1.val<head2.val:
                mergehead=head1
            else:
                mergehead=head2
        elif head1==None:
            return head2
        elif head2==None:
            return head1
        else:
            return None
        while head1!=None and head2!=None:
            if head1.val<head2.val:
                while head1.next!=None and head1.next.val<=head2.val:
                    head1=head1.next
                next1=head1.next
                head1.next=head2
                head1=next1
            else:
                while  head2.next!=None and head2.next.val<=head1.val:
                    head2=head2.next
                next2=head2.next
                head2.next=head1
                head2=next2
        return mergehead
複製代碼
相關文章
相關標籤/搜索