zoukankan      html  css  js  c++  java
  • [Leetcode] 24. Swap Nodes in Pairs

      在家瘫了半个月,虚弱时长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了

  • 相关阅读:
    ant-design-vue——子组件通过$parent修改父组件的值时无效问题及解决方法
    vue——quill-editor自定义图片上传
    ES6——var、let、const三者的区别
    js——数组/对象常用方法总结
    28.最长回文子序列
    27.马拉车
    26.扫雷一次点击
    JS添加内容之方法里传AJAX参数
    JQ 实现加载其他页面的H5代码 JQ加载H5独立导航栏代码
    CentOS 7不能上网 解决方法
  • 原文地址:https://www.cnblogs.com/alfredsun/p/11319731.html
Copyright © 2011-2022 走看看