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
相关推荐
郝学胜-神的一滴2 小时前
Leetcode 969 煎饼排序✨:翻转间的数组排序艺术
数据结构·c++·算法·leetcode·面试
I_LPL9 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
颜酱9 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
WolfGang00732110 小时前
代码随想录算法训练营 Day16 | 二叉树 part06
算法
2401_8318249611 小时前
代码性能剖析工具
开发语言·c++·算法
Sunshine for you12 小时前
C++中的职责链模式实战
开发语言·c++·算法
qq_4160187212 小时前
C++中的状态模式
开发语言·c++·算法
2401_8845632412 小时前
模板代码生成工具
开发语言·c++·算法
2401_8319207412 小时前
C++代码国际化支持
开发语言·c++·算法
m0_6727033112 小时前
上机练习第51天
数据结构·c++·算法