algorithm notes: leetcode#605 can place flowers

Problem


Analysis


Solution


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class :
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
cnt = 0
p0 = p1 = -2
for i, val in enumerate(flowerbed+[0]):
if val:
p1 = i
else:
p0 = i
if p0 - p1 > 2:
cnt += 1
p1 = i - 1
return cnt >= n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class :
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
left = n
p0 = p1 = -2
for i, val in enumerate(flowerbed+[0]):
if val:
p1 = i
else:
p0 = i
if p0 - p1 > 2:
left -= 1
p1 = i - 1
if left == 0:
return True
return False
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class :
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
cnt = 0
flowerbed = [0] + flowerbed + [0]
for i in range(1, len(flowerbed)-1):
if flowerbed[i] == flowerbed[i-1] == flowerbed[i+1] == 0:
flowerbed[i] = 1
cnt += 1
return cnt >= n

605. Can Place Flowers