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
相关推荐
Code哈哈笑3 分钟前
【机器学习】支持向量回归(SVR)从入门到实战:原理、实现与优化指南
人工智能·算法·机器学习·回归·svm
努力学习的小廉14 分钟前
【C++】 —— 笔试刷题day_29
开发语言·c++·算法
小羊在奋斗16 分钟前
【LeetCode 热题 100】搜索插入位置 / 搜索旋转排序数组 / 寻找旋转排序数组中的最小值
算法·leetcode·职场和发展
meisongqing22 分钟前
【软件工程】符号执行与约束求解缺陷检测方法
人工智能·算法·软件工程·软件缺陷
莫叫石榴姐43 分钟前
如何为大模型编写优雅且高效的提示词?
人工智能·算法
Echo``2 小时前
1:OpenCV—图像基础
c++·图像处理·人工智能·opencv·算法·计算机视觉·视觉检测
COOCC12 小时前
激活函数全解析:定义、分类与 17 种常用函数详解
人工智能·深度学习·神经网络·算法·机器学习·计算机视觉·自然语言处理
林下清风~3 小时前
力扣hot100——347.前K个高频元素(cpp手撕堆)
算法·leetcode·职场和发展
小雅痞3 小时前
[Java][Leetcode middle] 238. 除自身以外数组的乘积
java·leetcode
进击的小白菜4 小时前
Java回溯算法解决非递减子序列问题(LeetCode 491)的深度解析
java·算法·leetcode