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
相关推荐
珂朵莉MM6 分钟前
第七届全球校园人工智能算法精英大赛-算法巅峰赛产业命题赛第一赛季优化题--无人机配送
人工智能·算法·无人机
xiaoxue..18 分钟前
列表转树结构:从扁平列表到层级森林
前端·javascript·算法·面试
代码游侠25 分钟前
复习——线程(pthread)
linux·运维·开发语言·网络·学习·算法
papaofdoudou34 分钟前
基于QEMU 模拟intel-iommu的sva/svm demo环境搭建和验证
算法·机器学习·支持向量机
再__努力1点34 分钟前
【78】HOG+SVM行人检测实践指南:从算法原理到python实现
开发语言·人工智能·python·算法·机器学习·支持向量机·计算机视觉
scx2013100439 分钟前
20251214 字典树总结
算法·字典树
leiming641 分钟前
MobileNetV4 (MNv4)
开发语言·算法
YGGP1 小时前
【Golang】LeetCode 136. 只出现一次的数字
算法·leetcode
YGGP1 小时前
【Golang】LeetCode 169. 多数元素
算法·leetcode
顾安r1 小时前
11.20 脚本网页 数学分支
算法·数学建模·html