1. 程式人生 > 其它 >LeetCode-Python-605. 種花問題(陣列 + 貪心)

LeetCode-Python-605. 種花問題(陣列 + 貪心)

技術標籤:演算法陣列

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

給你一個整數陣列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

提示:

1 <= flowerbed.length <= 2 * 104

flowerbed[i] 為 0 或 1
flowerbed 中不存在相鄰的兩朵花
0 <= n <= flowerbed.length

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/can-place-flowers
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

思路:

貪心法,模擬種花的過程,能種就種。

時間複雜度:O(N)

空間複雜度:O(1)

class Solution(object):
    def canPlaceFlowers(self, flowerbed, n):
        """
        :type flowerbed: List[int]
        :type n: int
        :rtype: bool
        """

        for i, x in enumerate(flowerbed):
            if not x: # 空地
                if (i - 1 < 0 or flowerbed[i - 1] == 0) and (i + 1 == len(flowerbed) or flowerbed[i + 1] == 0): # 不衝突
                    flowerbed[i] = 1
                    n -= 1

        return n <= 0