Description
给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
Intro
Ref Link:https://leetcode.cn/problems/remove-duplicates-from-sorted-list/
Difficulty:Easy
Tag:LinkedList
Updated Date:2023-08-02
Test Cases
示例1:
输入:head = [1,1,2]
输出:[1,2]
示例 2:
输入:head = [1,1,2,3,3]
输出:[1,2,3]
提示:
链表中节点数目在范围 [0, 300] 内
-100 <= Node.val <= 100
题目数据保证链表已经按升序 排列
思路
- 链表遍历
Code AC
lass 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;
}
}
Accepted
166/166 cases passed (0 ms)
Your runtime beats 100 % of java submissions
Your memory usage beats 56.65 % of java submissions (41.7 MB)
复杂度分析
- 时间复杂度:O(n),其中 n 是链表的长度。
- 空间复杂度:O(1)