我開始完成一些 Leetcode 問題,完成了在線資料結構和演算法課程,但我很難理解一些輸入變數代表什么。我以其中一種解決方案為例。這個問題給了我一個排序鏈表的頭部作為輸入,并要求我洗掉所有重復項并回傳一個新的鏈表作為解決方案。
# 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]:
if head is None:
return head
pt=head
prev=pt
pt=pt.next
while pt:
if pt.val==prev.val:
# If the two nodes have the same value, then prev.next skips the current position of pt and moves two forward
prev.next=pt.next
pt=pt.next
else:
prev=pt
pt=pt.next
return head
我不明白的是這里“頭”這個詞的含義。例如,如果我作為(不正確的)解決方案只有一行代碼只回傳 head,則輸出將簡單地等于所有輸入,這意味著 head 只是自動迭代所有輸入值的指標除非另有指示。但是我還沒有設定任何迭代、while 回圈等,那么為什么 head 變數會自動在輸入串列的成員中移動呢?當然,通常情況下,head 只是指向鏈表第一個成員的指標。然后我們設定代碼,允許我們遍歷串列,同時可能會使用第二個指標等。
坦率地說,就此而言(在這里我將揭示我的困惑程度),我真的不明白指標通過鏈表迭代的歷史如何產生一組獨特的、非重復的可以在提供的解決方案中作為頭部回傳的值。Prev 是唯一跳過重復值的指標,據我了解('if pt.val == prev.val// prev.next = pt.next ...'),那么通過在這里回傳head,我們如何回傳上一頁的歷史...?任何幫助將非常感激。
uj5u.com熱心網友回復:
你可以試試這個:
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
temp = head
seen = set() # this will keep track if element is duplicate or not
prev = head # this will keep track of previous node
while temp:
if temp.val not in seen:
seen.add(temp.val)
prev = temp # update prev here only because if we update it in else as well then it can lead to point next of lost node you can get this by drawing this on paper
else:
prev.next = temp.next
temp = temp.next
return head
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/530227.html
