题目
代码
执行用时:52 ms, 在所有 Python3 提交中击败了59.24% 的用户
内存消耗:15.7 MB, 在所有 Python3 提交中击败了42.05% 的用户
通过测试用例:218 / 218
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
ans=None
now=None
while l1 and l2:
if l1.val<l2.val:
if ans==None:
ans=now=l1
else:
now.next=l1
now=l1
l1=l1.next
else:
if ans==None:
ans=now=l2
else:
now.next=l2
now=l2
l2=l2.next
while l1:
if ans==None:
ans=now=l1
else:
now.next=l1
now=l1
l1=l1.next
while l2:
if ans==None:
ans=now=l2
else:
now.next=l2
now=l2
l2=l2.next
return ans
【方法1的简化版本】
执行用时:52 ms, 在所有 Python3 提交中击败了59.24% 的用户
内存消耗:15.6 MB, 在所有 Python3 提交中击败了52.75% 的用户
通过测试用例:218 / 218
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
now=ans=ListNode(0)
while l1 and l2:
if l1.val<=l2.val:
now.next=l1
now=l1
l1=l1.next
else:
now.next=l2
now=l2
l2=l2.next
now.next=l1 if l1 else l2
return ans.next
【方法2】
执行用时:60 ms, 在所有 Python3 提交中击败了21.53% 的用户
内存消耗:17.5 MB, 在所有 Python3 提交中击败了6.06% 的用户
通过测试用例:218 / 218
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1:return l2
if not l2:return l1
if l1.val<=l2.val:
l1.next=self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next=self.mergeTwoLists(l1,l2.next)
return l2