Given a sorted linked list, delete all nodes that have duplicate
numbers, leaving only distinct numbers from the original list.
https://leetcode.com/problems...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: # Two nodes: one to keep head, one to keep tail. ahead = phead = ListNode("null") # Two pointers: one to move ahead, one to monitor duplicates. p = None c = head # When move to end, terminate. while c: # At the beginning, simple move one step forward. if p == None: p = c # If p and c have different values, need to determine why. elif p.val != c.val: # If p and c are neighbors, p must be unique value. if p.next == c: phead.next = p phead = phead.next phead.next = None # p gets one step forward. p = c # If p and c are not neighbors, ignore nodes with p.val. else: p = c # c moves one step anyway. c = c.next # If p is not None (input not empty) and has next, collect last element. if p != None and p.next == None: phead.next = p return ahead.next
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/43626.html
摘要:題目要求翻譯將鏈表中重復的元素全部刪除,返回新的頭結點。相比于,這里將重復的元素全部刪除。除此以外,我們還需要知道重復元素的前一個值和重復元素的最后一個值。如果存在重復值,則跳過重復值后,前節點不變,否則前節點跟隨后節點同時向后移動。 題目要求 Given a sorted linked list, delete all nodes that have duplicate number...
摘要:和上一道題不同的地方就是,需要用雙指針操作,且最后要返回,以防止結點即的情況返回錯誤的結果。令,用進行查重操作,是的前結點。當和等值的時候,后移至第一個不等值的點,用指向新的即可。 Remove Duplicates form Sorted List I Problem Given a sorted linked list, delete all duplicates such tha...
摘要:思路與代碼其實在這里我們仍然延續中的思路。在遇到非重復值以及非多余的重復值時,將數值移動到當前記錄的下標上。保證該下標前的值均為滿足題目條件的值。第一次我使用了來記錄某個值出現的次數。 題目要求 Follow up for Remove Duplicates: What if duplicates are allowed at most twice? For example, Giv...
摘要:自己沒事刷的一些的題目,若有更好的解法,希望能夠一起探討項目地址 自己沒事刷的一些LeetCode的題目,若有更好的解法,希望能夠一起探討 Number Problem Solution Difficulty 204 Count Primes JavaScript Easy 202 Happy Number JavaScript Easy 190 Reverse Bi...
摘要:微信公眾號記錄截圖記錄截圖目前關于這塊算法與數據結構的安排前。已攻略返回目錄目前已攻略篇文章。會根據題解以及留言內容,進行補充,并添加上提供題解的小伙伴的昵稱和地址。本許可協議授權之外的使用權限可以從處獲得。 Create by jsliang on 2019-07-15 11:54:45 Recently revised in 2019-07-15 15:25:25 一 目錄 不...
閱讀 3244·2021-11-11 11:00
閱讀 2565·2019-08-29 11:23
閱讀 1441·2019-08-29 10:58
閱讀 2323·2019-08-29 10:58
閱讀 2952·2019-08-23 18:26
閱讀 2507·2019-08-23 18:18
閱讀 2038·2019-08-23 16:53
閱讀 3411·2019-08-23 13:13