Source of the topic:
https://leetcode.com/problems/merge-k-sorted-lists/
Test Instructions Analysis:
Given a list of K-ordered lists, these linked lists are integrated into a new ordered list.
Topic Ideas:
We have already given two ways to integrate an orderly list. Here, we might as well use the idea of merge sort, the N list as the integration of N/2 and N-N/2, until N/2 <= 1. The time complexity is O (n * (2^log k)) = O (n * k).
Code (Python):
1 #Definition for singly-linked list.2 #class ListNode (object):3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classsolution (object):8 defmergetwolists (SELF,L1,L2):9 """Ten : Type L1:listnode One : Type L2:listnode A : Rtype:listnode - """ -Ans =listnode (0) theTMP =ans - ifL1 = = None andL2 = =None: - returnNone - whileL1!=noneorL2! =None: + ifL1 = =None: - whileL2! =None: +Tmp.val =L2.val AL2 =L2.next at ifL2 = =None: - Break -Tmp.next =listnode (0) -TMP =Tmp.next - Break - ifL2 = =None: in whileL1! =None: -Tmp.val =L1.val toL1 =L1.next + ifL1 = =None: - Break theTmp.next =listnode (0) *TMP =Tmp.next $ BreakPanax Notoginseng ifL1.val <=L2.val: -Tmp.val =L1.val theL1 =L1.next + Else: ATmp.val =L2.val theL2 =L2.next +Tmp.next =listnode (0) -TMP =Tmp.next $ returnans $ defmergeklists (self, lists): - """ - : Type Lists:list[listnode] the : Rtype:listnode - """WuyiSize =len (lists) the ifSize = =0: - returnNone Wu ifsize = = 1: - returnLists[0] Aboutn = size//2 $TMP1 =self.mergeklists (lists[:n]) -TMP2 =self.mergeklists (lists[n:]) - returnself.mergetwolists (TMP1,TMP2) -
View Code
Reprint Please specify source: http://www.cnblogs.com/chruny/p/4872905.html
[Leetcode] (python): 023-merge k Sorted Lists