LC 0082.Remove Duplicates from Sorted List II

题目描述

这是 LeetCode 上的 82. 删除排序链表中的重复元素 II ,难度为中等

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

示例 1:

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

示例 2:

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

提示:

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

解答

方法一:双指针

由于头指针可能也是重复的结点,所以要构造一个头指针的前结点,接下来判断结点的值是否存在重复的(可以用一个暂时变量来存储当前的值用于判断),如果存在重复的就不接入要返回的链表中,否则继续遍历链表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode res = new ListNode(0, head), cur = res;
while (cur.next != null && cur.next.next != null) {
if (cur.next.next.val == cur.next.val) {
int x = cur.next.val;
while (cur.next != null && cur.next.val == x) {
cur.next = cur.next.next;
}
} else {
cur = cur.next;
}

}
return res.next;
}
}
  • 时间复杂度\(O(N)\),其中 N 为链表的长度。

  • 空间复杂度\(O(1)\)

每题一图


LC 0082.Remove Duplicates from Sorted List II
https://chen-huaneng.github.io/2024/01/15/2024-1-15-2024-01-15-lc-0082/
作者
Abel
发布于
2024年1月15日
更新于
2024年1月15日
许可协议