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
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/43626.html
摘要:題目要求翻譯將鏈表中重復(fù)的元素全部刪除,返回新的頭結(jié)點(diǎn)。相比于,這里將重復(fù)的元素全部刪除。除此以外,我們還需要知道重復(fù)元素的前一個(gè)值和重復(fù)元素的最后一個(gè)值。如果存在重復(fù)值,則跳過重復(fù)值后,前節(jié)點(diǎn)不變,否則前節(jié)點(diǎn)跟隨后節(jié)點(diǎn)同時(shí)向后移動。 題目要求 Given a sorted linked list, delete all nodes that have duplicate number...
摘要:和上一道題不同的地方就是,需要用雙指針操作,且最后要返回,以防止結(jié)點(diǎn)即的情況返回錯(cuò)誤的結(jié)果。令,用進(jìn)行查重操作,是的前結(jié)點(diǎn)。當(dāng)和等值的時(shí)候,后移至第一個(gè)不等值的點(diǎn),用指向新的即可。 Remove Duplicates form Sorted List I Problem Given a sorted linked list, delete all duplicates such tha...
摘要:思路與代碼其實(shí)在這里我們?nèi)匀谎永m(xù)中的思路。在遇到非重復(fù)值以及非多余的重復(fù)值時(shí),將數(shù)值移動到當(dāng)前記錄的下標(biāo)上。保證該下標(biāo)前的值均為滿足題目條件的值。第一次我使用了來記錄某個(gè)值出現(xiàn)的次數(shù)。 題目要求 Follow up for Remove Duplicates: What if duplicates are allowed at most twice? For example, Giv...
摘要:自己沒事刷的一些的題目,若有更好的解法,希望能夠一起探討項(xiàng)目地址 自己沒事刷的一些LeetCode的題目,若有更好的解法,希望能夠一起探討 Number Problem Solution Difficulty 204 Count Primes JavaScript Easy 202 Happy Number JavaScript Easy 190 Reverse Bi...
摘要:微信公眾號記錄截圖記錄截圖目前關(guān)于這塊算法與數(shù)據(jù)結(jié)構(gòu)的安排前。已攻略返回目錄目前已攻略篇文章。會根據(jù)題解以及留言內(nèi)容,進(jìn)行補(bǔ)充,并添加上提供題解的小伙伴的昵稱和地址。本許可協(xié)議授權(quán)之外的使用權(quán)限可以從處獲得。 Create by jsliang on 2019-07-15 11:54:45 Recently revised in 2019-07-15 15:25:25 一 目錄 不...
閱讀 3253·2021-11-11 11:00
閱讀 2573·2019-08-29 11:23
閱讀 1456·2019-08-29 10:58
閱讀 2335·2019-08-29 10:58
閱讀 2960·2019-08-23 18:26
閱讀 2516·2019-08-23 18:18
閱讀 2048·2019-08-23 16:53
閱讀 3422·2019-08-23 13:13