zoukankan      html  css  js  c++  java
  • Leetcode python 206. 反转链表 83. 删除排序链表中的重复元素

    206. 反转链表

    给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

    示例 1:
    输入:head = [1,2,3,4,5]
    输出:[5,4,3,2,1]

    迭代

    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            pre, cur = None, head
            while cur:
                nxt = cur.next
                cur.next = pre
                pre = cur
                cur = nxt
            return pre
    

    执行用时:32 ms, 在所有 Python3 提交中击败了85.22%的用户
    内存消耗:15.5 MB, 在所有 Python3 提交中击败了56.20%的用户

    递归

    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            if not head or not head.next:
                return head
            newHead = self.reverseList(head.next)
            head.next.next = head
            head.next = None
            return newHead
    

    执行用时:36 ms, 在所有 Python3 提交中击败了65.86%的用户
    内存消耗:19.7 MB, 在所有 Python3 提交中击败了6.36%的用户

    83. 删除排序链表中的重复元素

    存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次

    返回同样按升序排列的结果链表。

    示例 1:
    输入:head = [1,1,2]
    输出:[1,2]

    示例 2:
    输入:head = [1,1,2,3,3]
    输出:[1,2,3]

    class Solution:
        def deleteDuplicates(self, head: ListNode) -> ListNode:
            if not head:
                return head
    
            cur = head
            while cur.next:
                if cur.val == cur.next.val:
                    cur.next = cur.next.next
                else:
                    cur = cur.next
    
            return head
    

    执行用时:40 ms, 在所有 Python3 提交中击败了60.98%的用户
    内存消耗:15 MB, 在所有 Python3 提交中击败了67.10%的用户

  • 相关阅读:
    kali linux 换国内源
    虚拟机桥接网络上网
    excel 无效引用 所引用的单元格不能位于256列
    sublime python配置运行
    java 环境变量配置(win10)
    Python错误:AssertionError: group argument must be None for now
    python if not
    ubuntu 安装mysql
    python 利用jieba库词频统计
    zxy的猪错误
  • 原文地址:https://www.cnblogs.com/hereisdavid/p/15322195.html
Copyright © 2011-2022 走看看