1. 程式人生 > 實用技巧 >Leetcode 82. Remove Duplicates from Sorted List II

Leetcode 82. Remove Duplicates from Sorted List II

Description: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

Link: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

Examples:

Example 1:
Input: 1->2->3->3->4->4->5
Output: 
1->2->5 Example 2: Input: 1->1->1->2->3 Output: 2->3

思路: 和83的區別在於,1) 只要這個元素出現過兩次及以上,就刪除,所以當前元素不僅要和前面的比較,還要和後面的比較,當與前後都不同時,才被新增到返回連結串列中,2) pre的更新也不同,83中,當pre和當前值不同時,才更新,相同則不更新,這裡要隨著指標移動而更新。3) 注意return linked list的head,如果從連結串列的第二個元素開始遍歷,需要先確認第一個元素是否unique.

# Definition for singly-linked list.
# class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return head
if not head.next: return head rhead = ListNode(0) r = rhead pre = head.val p = head.next if pre != p.val: r.next = head r = r.next while p: if p.val != pre and (p.next is None or p.val != p.next.val): r.next = p r = r.next pre = p.val p = p.next r.next = None return rhead.next

日期: 2020-11-17 週二就又過去了半天