LeetCode重点题系列之【20. Valid Parentheses】

本文介绍了一种高效的方法来合并多个已排序的链表成为一个单一的排序链表。通过递归地将链表分成两半并分别进行合并,最终实现了两两合并的功能。这种方法类似于归并排序,但背景是在链表上实现。

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

This is a hard problem??? Oh, it is! Actually, it's a very good problem, quite like merge sort. But the background is the list, LOL.

 

class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        if len(lists)==0:
            return None
        if len(lists)==1:
            return lists[0]
        l1=self.mergeKLists(lists[:len(lists)/2])
        l2=self.mergeKLists(lists[len(lists)/2:])
        return self.mergeTwoList(l1,l2)
    
    
    def mergeTwoList(self,l1,l2):
        dummy=ListNode(0)
        cur=dummy
        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
        if l1:
            cur.next=l1
        if l2:
            cur.next=l2
        return dummy.next

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值