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
相关推荐
Aaron158817 分钟前
AD9084和Versal RF系列具体应用案例对比分析
嵌入式硬件·算法·fpga开发·硬件架构·硬件工程·信号处理·基带工程
laocooon52385788618 分钟前
插入法排序 python
开发语言·python·算法
你的冰西瓜41 分钟前
C++中的list容器详解
开发语言·c++·stl·list
wuhen_n1 小时前
LeetCode -- 1:两数之和(简单)
javascript·算法·leetcode·职场和发展
林shir2 小时前
Java基础1.7-数组
java·算法
Jeremy爱编码3 小时前
leetcode课程表
算法·leetcode·职场和发展
甄心爱学习3 小时前
SVD求解最小二乘(手写推导)
线性代数·算法·svd
努力学算法的蒟蒻3 小时前
day46(12.27)——leetcode面试经典150
算法·leetcode·面试
Blockbuater_drug3 小时前
InChIKey: 分子的“化学身份证”,从哈希原理到全球监管合规(2025)
算法·哈希算法·inchikey·rdkit·分子表达·化学信息学
橙汁味的风3 小时前
2EM算法详解
人工智能·算法·机器学习