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
相关推荐
Geometry Fu9 分钟前
二叉树删除子树 (题目分析+C++代码实现)
数据结构·算法·图论
一缕叶17 分钟前
P8772 [蓝桥杯 2022 省 A] 求和
数据结构·c++·算法
金融OG1 小时前
99.12 金融难点通俗解释:毛利率
python·算法·机器学习·数学建模·金融
夏末秋也凉6 小时前
力扣-数组-283 移动零
算法·leetcode
jerry6096 小时前
回溯总结2(子集问题)
算法
苏苏大大6 小时前
【leetcode 23】54. 替换数字(第八期模拟笔试)
java·算法·leetcode
2401_858286118 小时前
CE10.【C++ Cont】练习题组11(进制转换专题)
开发语言·c++·算法
Bai_Yin10 小时前
Leetcode 189 轮转数组
java·数据结构·算法·leetcode
快敲啊死鬼10 小时前
代码随想录26
算法
字节高级特工11 小时前
【优选算法】----移动零
c++·算法