605. Can Place Flowers
https://leetcode.com/problems/can-place-flowers/
Python
First try
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
if not n:
return True
flowerbed = [0] + flowerbed + [0]
i = 1
while i < len(flowerbed)-1:
if flowerbed[i] == 1:
i += 1
continue
if flowerbed[i-1] == 0 and flowerbed[i+1] == 0:
n -= 1
flowerbed[i] = 1
if n == 0:
return True
i += 1
return False
Second Try
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
if not n:
return True
flowerbed = [0] + flowerbed + [0]
for i in range(1, len(flowerbed)-1):
if flowerbed[i] == 1:
continue
if flowerbed[i-1] == 0 and flowerbed[i+1] == 0:
n -= 1
flowerbed[i] = 1
if n == 0:
return True
return False