83. 删除排序链表中的重复元素

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

解法一:

用pre记录前驱,i往后遍历,遇到重复的就继续向前,直到非重复,然后修改pre的后继即可

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        pre = i = head
        while i:
            while i.next and i.val == i.next.val:
                i = i.next
            if pre != i:
                pre.next = i.next
                i = i.next
                pre = i
            else:
                i = i.next
                pre = i
        return head

解法二:

创建一个集合记录出现过的节点值,每次查表,遇到重复就跳过

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        s = set()    #出现过的值集
        Head = ListNode(0)
        Head.next = head
        pre, i = Head, head    #前驱和工作节点
        while i:
            if i.val in s:    #跳过重复
                pre.next = i.next
            else:
                s.add(i.val)    #第一次出现,写入值集
                pre = i
            i = i.next
        return Head.next

最后更新于