您的位置:首页 > 编程语言 > Python开发

Leetcode 23. Merge k Sorted Lists(python)

2016-04-07 17:44 741 查看
分治法两两合并,才没有超时

# 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
"""
if len(lists)==0:   return []
return self.merge(lists,0,len(lists)-1)

def merge(self,lists,l,r):
if l<r:
mid=(l+r)/2
return self.mergeTwoLists(self.merge(lists,l,mid),self.merge(lists,mid+1,r))
return lists[l]

def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res=cur=ListNode(0)

while l1 and l2:
if l1.val<l2.val:
cur.next=l1
l1=l1.next
else:
cur.next=l2
l2=l2.next
cur=cur.next
cur.next=l1 or l2
return res.next


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: