LeetCode 题解工作台

删除排序链表中的重复元素 II

给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。 示例 1: 输入: head = [1,2,3,3,4,4,5] 输出: [1,2,5] 示例 2: 输入: head = [1,1,1,2,3] 输出: [2,3] 提示: 链表中…

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

中等 · 链表指针操作

bolt

答案摘要

我们先创建一个虚拟头节点 ,令 $dummy.next = head$,然后创建指针 指向 ,指针 指向 ,开始遍历链表。 当 指向的节点值与 指向的节点值相同时,我们就让 不断向后移动,直到 指向的节点值与 指向的节点值不相同时,停止移动。此时,我们判断 是否等于 ,如果相等,说明 与 之间没有重复节点,我们就让 移动到 的位置;否则,说明 与 之间有重复节点,我们就…

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。

 

示例 1:

输入:head = [1,2,3,3,4,4,5]
输出:[1,2,5]

示例 2:

输入:head = [1,1,1,2,3]
输出:[2,3]

 

提示:

  • 链表中节点数目在范围 [0, 300]
  • -100 <= Node.val <= 100
  • 题目数据保证链表已经按升序 排列
lightbulb

解题思路

方法一:一次遍历

我们先创建一个虚拟头节点 dummydummy,令 dummy.next=headdummy.next = head,然后创建指针 prepre 指向 dummydummy,指针 curcur 指向 headhead,开始遍历链表。

curcur 指向的节点值与 cur.nextcur.next 指向的节点值相同时,我们就让 curcur 不断向后移动,直到 curcur 指向的节点值与 cur.nextcur.next 指向的节点值不相同时,停止移动。此时,我们判断 pre.nextpre.next 是否等于 curcur,如果相等,说明 preprecurcur 之间没有重复节点,我们就让 prepre 移动到 curcur 的位置;否则,说明 preprecurcur 之间有重复节点,我们就让 pre.nextpre.next 指向 cur.nextcur.next。然后让 curcur 继续向后移动。继续上述操作,直到 curcur 为空,遍历结束。

最后,返回 dummy.nextdummy.next 即可。

时间复杂度 O(n)O(n),其中 nn 为链表的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 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]:
        dummy = pre = ListNode(next=head)
        cur = head
        while cur:
            while cur.next and cur.next.val == cur.val:
                cur = cur.next
            if pre.next == cur:
                pre = cur
            else:
                pre.next = cur.next
            cur = cur.next
        return dummy.next
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Does the candidate correctly apply linked list pointer manipulation?

  • question_mark

    How does the candidate handle edge cases, such as empty or duplicate-only lists?

  • question_mark

    Is the solution optimal in terms of both time and space complexity?

warning

常见陷阱

外企场景
  • error

    Overcomplicating the problem with additional data structures.

  • error

    Not correctly linking the predecessor node when skipping duplicates.

  • error

    Failing to handle edge cases such as empty lists or all duplicates.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Implementing the solution recursively instead of iteratively.

  • arrow_right_alt

    Using a hash set to track duplicates (though this adds extra space complexity).

  • arrow_right_alt

    Modifying the list in-place without using extra pointers.

help

常见问题

外企场景

删除排序链表中的重复元素 II题解:链表指针操作 | LeetCode #82 中等