LC 0083.Remove Duplicates from Sorted List

题目描述

这是 LeetCode 上的 83. 删除排序链表中的重复元素 ,难度为简单

给定一个已排序的链表的头 head删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表

示例 1:

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

示例 2:

1
2
输入:head = [1,1,2,3,3]
输出:[1,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) {
if (head == null) {
return head;
}

ListNode cur = head;
while (cur.next != null) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}
  • 时间复杂度\(O(N)\),其中 N 为链表的长度。

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

每题一图


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