在家瘫了半个月,虚弱时长2月半,又来水题了~
内存感人,不过想不出来不用temp保存中间值的链表交换方法了。
Success
Details Runtime: 40 ms, faster than 44.76% of Python3 online submissions for Swap Nodes in Pairs.
Memory Usage: 13.6 MB, less than 6.06% of Python3 online submissions for Swap Nodes in Pairs.
Submission Detail
55 / 55 test cases passed.
|
Status:
Accepted |
Runtime: 40 ms
Memory Usage: 13.6 MB
|
Submitted: 2 minutes ago
|
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: # 0 if head == None: return head # 1 if head.next == None: return head # change head tempHead = head head = head.next tempHead.next = head.next head.next = tempHead #change Node after head currentprev = head.next current = head.next.next while True: if current != None and current.next != None: #do swap tempNext = current.next #node 4 current.next = current.next.next #node 3 point to 5 tempNext.next = current #node 4 point to 3 currentprev.next = tempNext#node 1 point to 4 #++1 if current.next !=None: currentprev = current current = currentprev.next else: break else: break return head
大佬的20ms:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def swapPairs(self, head): dummy = p = ListNode(0) dummy.next = head while head and head.next: tmp = head.next head.next = tmp.next tmp.next = head p.next = tmp head = head.next p = tmp.next return dummy.next
不过这个也是用的temp做交换啊 只是循环简单一点。。。怎么就只有20ms了