美文网首页Leetcode
[Leetcode]21. 合并两个有序链表

[Leetcode]21. 合并两个有序链表

作者: LeeYunFeng | 来源:发表于2019-03-21 22:48 被阅读0次

    题目描述:

    将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
    示例:

    • 输入:1->2->4, 1->3->4
    • 输出:1->1->2->3->4->4

    我的方法:

    这个题目比较简单,解法如下:

    1. 两个指针分别指向两个链表的头部。
    2. 比较对应位置的数字大小,记录较小的字符,对应的指针移到下一位。
    3. 直到两个链表都遍历完。

    效果还不错:执行用时 : 32 ms, 在Merge Two Sorted Lists的Python提交中击败了99.60% 的用户。内存消耗 : 10.8 MB, 在Merge Two Sorted Lists的Python提交中击败了0.57% 的用户。

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def mergeTwoLists(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            ans=ListNode(0)
            head=ans
            while l1 and l2:
                if l1.val <= l2.val:
                    ans.next=l1
                    ans=ans.next # 注意:ans也要移动
                    l1=l1.next
                else:
                    ans.next=l2
                    ans=ans.next # 注意:ans也要移动
                    l2=l2.next
            ans.next=l1 if l1 else l2
            return head.next
                    
    

    别人的方法:

    也有人用递归的方法,虽然速度略慢,但思路依然可以借鉴。处理步骤如下:

    1. mergeTwoLists(self,l1,l2)的主要功能,是将两个有序链表合成一个有序链表。递归只需要关注移动和终止条件两个问题。
    2. 终止条件是l1为空或者l2为空。如果l1为空,则返回l2;如果l2为空,则返回l1。
    3. 递归事实上是问题拆解为子问题的过程,本题是将merge(l1,l2)转化为merge(l1.next,l2)或者merge(l1,l2.next)。通过这种转化,实现链表的移动。
    4. 最终返回head.next。

    最终运行效率一般,递归的效率一般都不是最高的。执行用时 : 36 ms, 在Merge Two Sorted Lists的Python提交中击败了50.40% 的用户。内存消耗 : 10.9 MB, 在Merge Two Sorted Lists的Python提交中击败了0.57% 的用户。

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def mergeTwoLists(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            # 终止条件
            if not l1: return l2
            if not l2: return l1
            
            head = ListNode(0)
            # 当l1.val<l2.val,则l1向后移动一位
            if l1.val < l2.val:
                l1.next = self.mergeTwoLists(l1.next, l2)
                head.next = l1
            # 否则,l2向后移动一位
            else:
                l2.next = self.mergeTwoLists(l1, l2.next)
                head.next = l2
                
            return head.next
    

    相关文章

      网友评论

        本文标题:[Leetcode]21. 合并两个有序链表

        本文链接:https://www.haomeiwen.com/subject/ooahvqtx.html