LeetCode Python - 82. 删除排序链表中的重复元素 II

目录


题目描述

给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。

示例 1:

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

输出:[1,2,5]

示例 2:

输入:head = [1,1,1,2,3]

输出:[2,3]

提示:

  • 链表中节点数目在范围 [0, 300] 内
  • -100 <= Node.val <= 100
  • 题目数据保证链表已经按升序 排列

解法

我们先创建一个虚拟头节点 dummy,令 dummy.next=head,然后创建指针 pre 指向 dummy,指针 cur 指向 head,开始遍历链表。

当 cur 指向的节点值与 cur.next 指向的节点值相同时,我们就让 cur 不断向后移动,直到 cur 指向的节点值与 cur.next 指向的节点值不相同时,停止移动。此时,我们判断 pre.next 是否等于 cur,如果相等,说明 pre 与 cur 之间没有重复节点,我们就让 pre 移动到 cur 的位置;否则,说明 pre 与 cur 之间有重复节点,我们就让 pre.next 指向 cur.next。然后让 cur 继续向后移动。继续上述操作,直到 cur 为空,遍历结束。

最后,返回 dummy.next 即可。

时间复杂度 O(n),其中 n 为链表的长度。空间复杂度 O(1)。

python 复制代码
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        dummy = pre = ListNode(next=head)
        cur = head
        while cur:
            while cur.next and cur.next.val == cur.val:
                cur = cur.next
            if pre.next == cur:
                pre = cur
            else:
                pre.next = cur.next
            cur = cur.next
        return dummy.next
        

运行结果

相关推荐
Dream it possible!2 分钟前
LeetCode 面试经典 150_链表_反转链表 II(60_92_C++_中等)(头插法)
c++·leetcode·链表·面试
闲人编程25 分钟前
Python设计模式实战:用Pythonic的方式实现单例、工厂模式
开发语言·python·单例模式·设计模式·工厂模式·codecapsule·pythonic
py有趣2 小时前
LeetCode学习之实现strStr()
学习·算法·leetcode
lang201509282 小时前
Spring环境配置与属性管理完全指南
java·python·spring
夏鹏今天学习了吗2 小时前
【LeetCode热题100(52/100)】课程表
算法·leetcode·职场和发展
祁思妙想2 小时前
【LeetCode100】--- 101.重排链表【思维导图+复习回顾】
算法·leetcode·链表
Dream it possible!2 小时前
LeetCode 面试经典 150_链表_随机链表的复制(59_138_C++_中等)
c++·leetcode·链表
懒惰蜗牛2 小时前
Day10:Python实现Excel自动汇总
python·numpy·pandas·pip·1024程序员节·python读写excel
我是华为OD~HR~栗栗呀2 小时前
华为od-22届考研-C++面经
java·前端·c++·python·华为od·华为·面试
m0_748240252 小时前
华为OD机考:计算正方形数量(Python & C/C++ & JAVA & JS & GO)
c语言·python·华为od