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
相关推荐
平和男人杨争争15 分钟前
机器学习12——支持向量机中
算法·机器学习·支持向量机
10岁的博客32 分钟前
代码编程:一场思维与创造力的革命
开发语言·算法
Aczone281 小时前
嵌入式 数据结构学习 (六) 树、哈希表与内核链表
数据结构·学习·算法
定偶1 小时前
进制转换小题
c语言·开发语言·数据结构·算法
体系结构论文研讨会2 小时前
多项式环及Rq的含义
算法
智驱力人工智能2 小时前
极端高温下的智慧出行:危险检测与救援
人工智能·算法·安全·行为识别·智能巡航·高温预警·高温监测
森焱森2 小时前
60 美元玩转 Li-Fi —— 开源 OpenVLC 平台入门(附 BeagleBone Black 驱动简单解析)
c语言·单片机·算法·架构·开源
课堂剪切板3 小时前
ch07 题解
算法·深度优先
科大饭桶4 小时前
数据结构自学Day5--链表知识总结
数据结构·算法·leetcode·链表·c
我爱C编程6 小时前
基于Qlearning强化学习的1DoF机械臂运动控制系统matlab仿真
算法