【力扣】605.種花問題--Python實現
阿新 • • 發佈:2021-01-20
【題目描述】
假設有一個很長的花壇,一部分地塊種植了花,另一部分卻沒有。可是,花不能種植在相鄰的地塊上,它們會爭奪水源,兩者都會死去。
給你一個整數陣列 flowerbed 表示花壇,由若干 0 和 1 組成,其中 0 表示沒種植花,1 表示種植了花。另有一個數 n ,能否在不打破種植規則的情況下種入 n 朵花?能則返回 true ,不能則返回 false。
示例 1:
輸入:flowerbed = [1,0,0,0,1], n = 1
輸出:true
示例 2:
輸入:flowerbed = [1,0,0,0,1], n = 2
輸出:false
提示:
flowerbed[i] 為 0 或 1
flowerbed 中不存在相鄰的兩朵花
0 <= n <= flowerbed.length
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/can-place-flowers
【解題思路】
貪心法,有三種可能性:
0
00100
10001
分別對應著:
len(flowerber)==0
為首或者為尾且相鄰的元素為0
為中間元素且左右都為0
用Python實現的程式碼如下:
class Solution(object): def canPlaceFlowers(self, flowerbed, n): """ :type flowerbed: List[int] :type n: int :rtype: bool """ for i in range(len(flowerbed)): if n==0: return True if flowerbed[i]==0: if len(flowerbed)==1: n -= 1 elif i==0 and flowerbed[i+1]==0: n -= 1 flowerbed[i]=1 elif i==len(flowerbed)-1 and flowerbed[i-1]==0: n -= 1 flowerbed[i]=1 elif 0<i<len(flowerbed)-1 and flowerbed[i-1]==0 and flowerbed[i+1]==0: n -= 1 flowerbed[i]=1 if n==0: return True else: return False