Algorithm I 筆記撰寫計畫 第八天第二題,共兩題。
- 難度:
Easy
- 花費時間: 30 min
- 題目: 83. Remove Duplicates from Sorted List
給你一個 Linked List
的 head
,刪除所有重複的節點,然後回傳新的 Linked List
點我開啟限制與範例
限制:
- The number of nodes in the list is in the range
[0, 300]
. -100 <= Node.val <= 100
- The list is guaranteed to be sorted in ascending order.
Example 1:
1 | Input: head = [1,1,2] |
Example 2:
1 | Input: head = [1,1,2,3,3] |
Definition for singly-linked list.
1 | class ListNode { |
筆記
這題簡單的讓我們練習了一下 Linked List
步驟如下
- 遍歷
List
- 每個
Node
都跟Node.next
做比較- 如果相等: 把
Node.next
指向Node.next.next
重複直到不相等
- 如果相等: 把
- 回傳
Head
TS iterative solution.
1 | function deleteDuplicates(head: ListNode | null): ListNode | null { |
Java recursive solution.
1 | class Solution { |
成績
Language | Runtime | Beats | Memory Usage | Beats |
---|---|---|---|---|
Java | 1 ms | 80.63% | 43.9 MB | 73.27% |
TypeScript | 77 ms | 95.35% | 45.4 MB | 22.74% |