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
相关推荐
陌路203 分钟前
S12 简单排序算法--冒泡 选择 直接插入 希尔排序
数据结构·算法·排序算法
雾岛—听风38 分钟前
P1012 [NOIP 1998 提高组] 拼数
算法
papership1 小时前
【入门级-算法-5、数值处理算法:高精度的乘法】
数据结构·算法
earthzhang20211 小时前
【1039】判断数正负
开发语言·数据结构·c++·算法·青少年编程
谈笑也风生1 小时前
只出现一次的数字 II(一)
数据结构·算法·leetcode
蕓晨1 小时前
auto 自动类型推导以及注意事项
开发语言·c++·算法
mjhcsp2 小时前
C++ 递推与递归:两种算法思想的深度解析与实战
开发语言·c++·算法
_OP_CHEN2 小时前
算法基础篇:(三)基础算法之枚举:暴力美学的艺术,从穷举到高效优化
c++·算法·枚举·算法竞赛·acm竞赛·二进制枚举·普通枚举
m0_748248022 小时前
《详解 C++ Date 类的设计与实现:从运算符重载到功能测试》
java·开发语言·c++·算法
天选之女wow2 小时前
【代码随想录算法训练营——Day61】图论——97.小明逛公园、127.骑士的攻击
算法·图论