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
相关推荐
橘子汽水1682 小时前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
huameinan狮子2 小时前
Adaboost算法原理与计算实例
算法
别怪我很水2 小时前
API中提供了VelocityTracker类用于计算触摸事件MotionEvent的速度,而其内部默认使用的方法就是最小二乘法,本 ...
算法·gitee·最小二乘法
Re.不晚6 小时前
挑战做100道力扣算法- DAY1
算法·leetcode·职场和发展
蓝悦无人机6 小时前
《Planning algorithms》读书笔记——第1章 引言
算法·读书笔记·规划算法·lavalle
Sagittarius_A*6 小时前
分组密码基础(二):Feistel 结构与 DES 的设计思想
算法·信息安全·密码学·des·数论
青山木6 小时前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode
alexwang2117 小时前
HDU 4348 详细题解
c++·算法·题解·hdu·主席树·可持久化数据结构·可持久化线段树
可编程芯片开发8 小时前
基于分段变步长搜索RMDCFT算法的天基雷达空间机动目标检测方法MATLAB仿真,对比RMDCFT算法
算法