leetcode - 82. Remove Duplicates from Sorted List II

Description

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

Example 1:

复制代码
Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]

Example 2:

复制代码
Input: head = [1,1,1,2,3]
Output: [2,3]

Constraints:

复制代码
The number of nodes in the list is in the range [0, 300].
-100 <= Node.val <= 100
The list is guaranteed to be sorted in ascending order.

Solution

Use a prev to record the previous node, and if the current node is duplicated by the next node, delete them. Otherwise move prev forward.

Time complexity: o ( n ) o(n) o(n)

Space complexity: o ( 1 ) o(1) o(1)

Code

python3 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        ret_head = ListNode(-1)
        ret_head.next = head
        prev, p = ret_head, ret_head.next
        while p and p.next:
            pn = p.next
            need_delete = False
            while pn and pn.val == p.val:
                need_delete = True
                pn = pn.next
            if need_delete:
                prev.next = pn
                p = prev.next
            else:
                prev, p = prev.next, p.next
        return ret_head.next
相关推荐
mit6.82419 分钟前
[贪心_7] 最优除法 | 跳跃游戏 II | 加油站
数据结构·算法·leetcode
keep intensify21 分钟前
通讯录完善版本(详细讲解+源码)
c语言·开发语言·数据结构·算法
shix .28 分钟前
2025年PTA天梯赛正式赛 | 算法竞赛,题目详解
数据结构·算法
风铃儿~37 分钟前
Java面试高频问题(26-28)
java·算法·面试
wuqingshun31415939 分钟前
蓝桥杯 4. 卡片换位
算法·职场和发展·蓝桥杯
江沉晚呤时41 分钟前
深入了解C# List集合及两种常见排序算法:插入排序与堆排序
windows·sql·算法·oracle·c#·排序算法·mybatis
Eric.Lee20211 小时前
数据集-目标检测系列- F35 战斗机 检测数据集 F35 plane >> DataBall
人工智能·算法·yolo·目标检测·计算机视觉
Gsen28191 小时前
AI大模型从0到1记录学习 数据结构和算法 day20
数据结构·学习·算法·生成对抗网络·目标跟踪·语言模型·知识图谱
一定要AK1 小时前
天梯——L1-110 这不是字符串题
数据结构·c++·算法
2401_858286112 小时前
E47.【C语言】零散的练习题(1)
c语言·数据结构·算法·指针