1. 程式人生 > >leetcode-605. 種花問題

leetcode-605. 種花問題

一、題目描述

假設你有一個很長的花壇,一部分地塊種植了花,另一部分卻沒有。可是,花卉不能種植在相鄰的地塊上,它們會爭奪水源,兩者都會死去。

給定一個花壇(表示為一個數組包含0和1,其中0表示沒種植花,1表示種植了花),和一個數 。能否在不打破種植規則的情況下種入 朵花?能則返回True,不能則返回False。

示例 1:

輸入: flowerbed = [1,0,0,0,1], n = 1
輸出: True

示例 2:

輸入: flowerbed = [1,0,0,0,1], n = 2
輸出: False

注意:

  1. 陣列內已種好的花不會違反種植規則。
  2. 輸入的陣列長度範圍為 [1, 20000]。
  3. n 是非負整數,且不會超過輸入陣列的大小。

二、程式碼和思路

    設定m,count,num,i分別為flowerbed的長度、連續0的個數、可種植植物的數目、遍歷陣列的標準位

    這裡首先對flowerbed陣列的長度進行檢查如果為1且陣列內元素為0則num += 1

    整個迴圈過程中先對陣列首尾預判,這裡首尾對是否能種植植物的標準跟中間打的不一樣,只要首尾分別有連續兩個0即可種植一顆植物,然而在陣列中只能碰到連續的三個0才能種植一顆植物,種植完都將count記為1繼續記錄count值

class Solution(object):
    def canPlaceFlowers(self, flowerbed, n):
        """
        :type flowerbed: List[int]
        :type n: int
        :rtype: bool
        """
        m,count,num,i=len(flowerbed),0,0,0
        if m==1 and flowerbed[0]==0:
            num += 1
        while i<m:
            if flowerbed[i]==0:
                count += 1
                if (i==1 or i==m-1) and count==2:
                    num += 1
                    count=1
                if count==3:
                    num += 1
                    count=1
            else:
                count=0
            if num>=n:
                return True
            i += 1            
        return False   

三、執行結果