Description
給定一個已排序的鏈表的頭 head , 刪除所有重復的元素,使每個元素只出現(xiàn)一次 。返回 已排序的鏈表 。
Intro
Ref Link:https://leetcode.cn/problems/remove-duplicates-from-sorted-list/
Difficulty:Easy
Tag:LinkedList
Updated Date:2023-08-02
Test Cases
示例1:文章來源:http://www.zghlxwxcb.cn/news/detail-629987.html
輸入:head = [1,1,2]
輸出:[1,2]
示例 2:文章來源地址http://www.zghlxwxcb.cn/news/detail-629987.html
輸入:head = [1,1,2,3,3]
輸出:[1,2,3]
提示:
鏈表中節(jié)點數(shù)目在范圍 [0, 300] 內
-100 <= Node.val <= 100
題目數(shù)據(jù)保證鏈表已經按升序 排列
思路
- 鏈表遍歷
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)
到了這里,關于Killing LeetCode [83] 刪除排序鏈表中的重復元素的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!