80. Remove Duplicates from Sorted Array II

簡介

Follow up for "Remove Duplicates":What if duplicates are allowed at most twice?
For example,Given sorted array nums = [1,1,1,2,2,3]
Your function should return length = 5
with the first five elements of nums being 1, 1, 2, 2and 3
It doesn't matter what you leave beyond the new length

總體和26題的思路差不多

代碼(python)

class Solution(object):
    
    def if_dp(self):
        last1 = yield
        last2 = yield False
        cur = yield False

        while True:
            next = yield (last1 == cur == last2)
            last1,last2,cur =last2,cur,next

    def delete_dup(self,l,p):
        i = 0
        for j in range(0,len(l)):
            if p(l[j]):
                continue

            l[i] = l[j]
            i += 1
    
        return i
    
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        p = self.if_dp()
        next(p)
        return self.delete_dup(nums,p.send)

之前的理解上出現(xiàn)了偏差,主要是在send和yield上的理解上
send和yield是兩個分開的工作,或者說send在完成next的情況下,自己的
send也有自己的進程

send的例子

def test():
    while True:
        k = yield 
        m = yield
        if k == 4:
            print('aa')
        if m == 4:
            print('hello')
p = test()
next(p)
p.send(4)
next(p)

我們分析這段代碼,當next的時候k被過去了,generator下一次的返回值是 m = yield
這句的yield,send的值傳給的是k,而返回的是 m = yield這句,再next的時候
print('aa')

分析代碼

1.分別傳進nums[0],nums[1],nums[2]給last1,last2,cur,而另一方面
分別返回的是
False : nums[0]
False : nums[1]
此時i = 2 為一個判斷點,此時nums[2]傳給cur用來返回前三個點是否相同

2.之后的時候nums[3]則直接對應(yīng)的是返回的是否相同
意思就是說,我傳進一個值作為next,然后三個last1,last2,cur 分別向后轉(zhuǎn)變

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容