Leetcode 21. Merge Two Sorted Lists
一开始解决方式(特别慢,特别乱: beat 10%+ 我个菜
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 == None:
return l2
if l2 == None:
return l1
k = ListNode(0)
if l1.val <= l2.val:
keepList = l1
aList = l2
k.next = l1
else:
keepList = l2
aList = l1
k.next = l2
while aList:
indexVal = keepList.val
#print(indexVal)
#print(aList.val)
if (aList.val >= indexVal):
if(keepList.next == None):
keepList.next = aList
break
else:
if(keepList.next.val > aList.val):
if(aList.next == None or aList.next.val >= keepList.next.val):
temp = aList.next
aList.next = keepList.next
keepList.next = aList
aList = temp
keepList = keepList.next.next
else:
temp = keepList.next
keepList.next = aList
keepList = keepList.next.next
aList = temp
else:
keepList = keepList.next
return k.next
第二次: 60% + 就是运行时间不知道为什么比较玄学,代码如下:
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 == None:
return l2
if l2 == None:
return l1
root = ListNode(0)
cur = root
while l1 and l2:
if(l1.val <= l2.val):
cur.next = ListNode(l1.val)
l1 = l1.next
else:
cur.next = ListNode(l2.val)
l2 = l2.next
cur = cur.next
if l1:
cur.next = l1
if l2:
cur.next = l2
return root.next
决定看Discuss:
解法1. 也不太快的递归解法:(但是就是很神奇 Genius!
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
return l2
elif not l2:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
well.好像其他解法也不太快的样子,可能是python语言本身的问题?(逃...