LeetCode 题解工作台
删除排序链表中的重复元素 II
给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。 示例 1: 输入: head = [1,2,3,3,4,4,5] 输出: [1,2,5] 示例 2: 输入: head = [1,1,1,2,3] 输出: [2,3] 提示: 链表中…
2
题型
8
代码语言
3
相关题
当前训练重点
中等 · 链表指针操作
答案摘要
我们先创建一个虚拟头节点 ,令 $dummy.next = head$,然后创建指针 指向 ,指针 指向 ,开始遍历链表。 当 指向的节点值与 指向的节点值相同时,我们就让 不断向后移动,直到 指向的节点值与 指向的节点值不相同时,停止移动。此时,我们判断 是否等于 ,如果相等,说明 与 之间没有重复节点,我们就让 移动到 的位置;否则,说明 与 之间有重复节点,我们就…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路
题目描述
给定一个已排序的链表的头 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- 题目数据保证链表已经按升序 排列
解题思路
方法一:一次遍历
我们先创建一个虚拟头节点 ,令 ,然后创建指针 指向 ,指针 指向 ,开始遍历链表。
当 指向的节点值与 指向的节点值相同时,我们就让 不断向后移动,直到 指向的节点值与 指向的节点值不相同时,停止移动。此时,我们判断 是否等于 ,如果相等,说明 与 之间没有重复节点,我们就让 移动到 的位置;否则,说明 与 之间有重复节点,我们就让 指向 。然后让 继续向后移动。继续上述操作,直到 为空,遍历结束。
最后,返回 即可。
时间复杂度 ,其中 为链表的长度。空间复杂度 。
# 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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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?
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.