leetcode 605. gardening questions (python)

Topic Link

Subject description:

Suppose you have a long flower bed, part of plots planted with flowers, the other part did not. However, the flowers can not grow on the adjacent land, they compete for water, both will die.

Given a flower bed (represented as an array including 0 and 1, where 0 represents no planting flowers, flowers planted represents 1), and a number n. You can grow without breaking the rules of the n planting flowers? It can return True, False if not.

Example 1:

Input: flowerbed = [1,0,0,0,1], n = 1
Output: True
Example 2:

Input: flowerbed = [1,0,0,0,1], n = 2
Output: False

Problem-solving ideas:

Were added at both the list 0 boundary problem for processing, go through the list, if the current value is 0, and a front and back are 0, the current value to 1, and the number can be added to the gardening 1 .

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        count=0
        flowerbed=[0]+flowerbed+[0]
        for i in range(1,len(flowerbed)-1):
            if flowerbed[i]==0 and flowerbed[i-1]==0 and flowerbed[i+1]==0:
                flowerbed[i]=1
                count+=1
        return count>=n

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_44740082/article/details/90963795