Promble
link: https://leetcode.com/problems/can-place-flowers/description/
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0’s and 1’s, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
Approach
Thought
- def count:int to store the empty plot.
- if n == 0, dont input the flower, return True.
- loop i in range(len(flowerbed)).
- check flowerbed[i] is empty.
- check left and right is empty.
- when left, right is empty:
- flowerbed[i] = 1 # input the flow.
- count += 1.
- check count >= n: return True.
- check flowerbed[i] is empty.
- if not, return False.
Code
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
count = 0
if n == 0:
return True
for i in range(len(flowerbed)):
if flowerbed[i] == 0:
# check left and right
left = (i==0) or (flowerbed[i-1] == 0)
right = (i==len(flowerbed)-1) or (flowerbed[i+1]==0)
if left and right:
flowerbed[i] = 1
count += 1
if count >= n:
return True
return False