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
相关推荐
2301_8002561128 分钟前
8.2 空间查询基本组件 核心知识点总结
数据库·人工智能·算法
不穿格子的程序员29 分钟前
从零开始写算法——矩阵类题:矩阵置零 + 螺旋矩阵
线性代数·算法·矩阵
资深web全栈开发1 小时前
LeetCode 3432. 统计元素和差值为偶数的分区方案数
算法·leetcode
黎茗Dawn1 小时前
DDPM-KL 散度与 L2 损失
人工智能·算法·机器学习
wearegogog1231 小时前
DEA模型MATLAB实现(CCR、BCC、超效率)
开发语言·算法·matlab
业精于勤的牙1 小时前
浅谈:快递物流与算法的相关性(四)
算法
ghie90901 小时前
MATLAB自适应子空间辨识工具箱
数据结构·算法·matlab
过河卒_zh15667661 小时前
算法备案最新通知:26年1月批备案号发放名单已锁定,发放前的复审抽审已开始
人工智能·算法·aigc·算法备案
cici158741 小时前
基于反向传播算法实现手写数字识别的MATLAB实现
开发语言·算法·matlab
老欧学视觉1 小时前
0013机器学习聚类算法(无监督算法)
算法·机器学习·聚类