LeetCode-82. 刪除排序鏈表中的重復元素 II【鏈表 雙指針】
- 題目描述:
- 解題思路一:用一個cur即可實現去重cur.next = cur.next.next
- 背誦版:
- 解題思路三:0
題目描述:
給定一個已排序的鏈表的頭 head , 刪除原始鏈表中所有重復數字的節點,只留下不同的數字 。返回 已排序的鏈表 。
示例 1:
輸入:head = [1,2,3,3,4,4,5]
輸出:[1,2,5]
示例 2:
輸入:head = [1,1,1,2,3]
輸出:[2,3]
提示:
鏈表中節點數目在范圍 [0, 300] 內
-100 <= Node.val <= 100
題目數據保證鏈表已經按升序 排列
解題思路一:用一個cur即可實現去重cur.next = cur.next.next
class Solution:def deleteDuplicates(self, head: ListNode) -> ListNode:if not head:return headdummy = ListNode(0, head)cur = dummywhile cur.next and cur.next.next:if cur.next.val == cur.next.next.val:x = cur.next.valwhile cur.next and cur.next.val == x:cur.next = cur.next.nextelse:cur = cur.nextreturn dummy.next
時間復雜度:O(n)
空間復雜度:O(1)
背誦版:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:cur = dummy = ListNode(next = head)while cur.next and cur.next.next:val = cur.next.valif val == cur.next.next.val:while cur.next and cur.next.val == val:cur.next = cur.next.nextelse:cur = cur.nextreturn dummy.next
時間復雜度:O(n)
空間復雜度:O(1)
解題思路三:0
時間復雜度:O(n)
空間復雜度:O(n)

? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ?