605. 種花問題

題目python

python

class Solution:
    def canPlaceFlowers(self, flowerbed, n):
        """
        :type flowerbed: List[int]
        :type n: int
        :rtype: bool
        """
        
        count = 0
        flowerbed.insert(0,0)
        flowerbed.append(0)
        
        for i,x in enumerate(flowerbed):
            if x == 0:
                count += 1
            else:
                count = 0
                
            if count == 3:
                count = 1
                flowerbed[i -1] = 1
                n -= 1

        
        return n <= 0

思路:
加一個頭,加一個尾,這樣能夠保證原來的列表中,開頭和末尾均可以加入元素。app

從頭開始,記錄連續爲0的數量,當計數count爲3,那麼中間位置插入一個1,此時能夠種花的數量n減去1,而且0計數count從1開始。spa

一直到末尾,最終的n值是否小於0。code

相關文章
相關標籤/搜索