ZhongKuo0228 / study

0 stars 0 forks source link

605. Can Place Flowers #62

Open fockspaces opened 11 months ago

fockspaces commented 11 months ago

真的種花判斷能否種完即可 這邊邊界判斷有兩種做法:

  1. 補丁邊界,再從 1 ~ n - 2 開始找
  2. 對 0, n -1 處做特殊判斷,如果碰到界外則視作 0 -> 比較偏好這做法
class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        for i in range(len(flowerbed)):
            left = flowerbed[i - 1] if i - 1 >= 0 else 0
            right = flowerbed[i + 1] if i + 1 < len(flowerbed) else 0
            if left == 0 and right == 0 and flowerbed[i] == 0:
                 flowerbed[i] = 1
                 n -= 1
        return n <= 0