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

Leetcode 83. Remove Duplicates from Sorted List

Description: Given a sorted linked list, delete all duplicates such that each element appear only once.

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

思路: 我們會如何刪除list的重複元素呢?很簡單,我們會記錄前一個元素的值,然後與當前元素進行比較,相同則略過,不同則加入要返回的list中。。那麼我們只需要將對list的操作換成連結串列就可以了,但特別值得注意的是,我們如果結尾兩個元素相同,我們將倒數第二個元素加入新的連結串列,一定要將node.next = None

,否則就會將後面的全部加入,是錯的。

a = [1,1,2,3,3]
pre = a[0]
b = []
b.append(pre)
for i in a[1:]:
    if i != pre:
        b.append(i)
        pre = i
print(b)    

換成linkedlist:

# 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 = head r = rhead p = head.next pre = head.val
while p: # print(pre) if p.val != pre: pre = p.val r.next = p r = r.next p = p.next r.next = None return rhead

如果直接在原連結串列上進行刪除,不新增新的連結串列,時間會增加,空間會稍減少:

# 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
        
        pre = head # moving node of the returned linkedlist
        cur = head.next
        while cur:
            if cur.val == pre.val:
                pre.next = cur.next  #remove current node
            else:
                pre.next = cur #join current node
                pre = pre.next #point to the next
            cur = cur.next
        return head      
        

日期: 2020-11-17 晨跑很舒服,是元氣滿滿的一天,不要焦慮,要充實