首页 > 其他 > 详细

[leetcode]21. Merge Two Sorted Lists

时间:2019-05-28 00:14:03      阅读:143      评论:0      收藏:0      [点我收藏+]

突然发现代码开头的注释取消注释就是ListNode的定义,可以本地调试了。。。

这道题注意两个链表可以同时为None.

 

Runtime: 44 ms, faster than 86.67% of Python3 online submissions forMerge Two Sorted Lists.
Memory Usage: 13 MB, less than 86.39% of Python3 online submissions forMerge Two Sorted Lists.
 

Submission Detail

208 / 208 test cases passed.
Status: 

Accepted

Runtime: 44 ms
Memory Usage: 13 MB
Submitted: 0 minutes ago

 

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        #0
        if l1 == None and l2 == None:
            return l1
        if l1 == None:
            return l2
        if l2 == None:
            return l1
        # init
        if l1.val >= l2.val:
            ret = ListNode(l2.val)
            ret.next = None
            l2 = l2.next
        else:
            ret = ListNode(l1.val)
            ret.next = None
            l1 = l1.next
        retu =ret
        # normal
        while (l1 != None or l2 != None):
            # none
            if l1 == None:
                ret.next = l2
                return retu
            if l2 == None:
                ret.next = l1
                return retu
            # normal
            if l1.val >= l2.val:
                ret.next = ListNode(l2.val)
                ret = ret.next
                l2 = l2.next
            else:
                ret.next = ListNode(l1.val)
                ret = ret.next
                l1 = l1.next
        return retu

 

[leetcode]21. Merge Two Sorted Lists

原文:https://www.cnblogs.com/alfredsun/p/10934419.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!