Skip to content

Commit df76a90

Browse files
authored
Create can-place-flowers.py
1 parent 6dae5b4 commit df76a90

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Python/can-place-flowers.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# Suppose you have a long flowerbed in which some of the plots are planted and some are not.
5+
# However, flowers cannot be planted in adjacent plots - they would compete for water
6+
# and both would die.
7+
#
8+
# Given a flowerbed (represented as an array containing 0 and 1,
9+
# where 0 means empty and 1 means not empty), and a number n,
10+
# return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.
11+
#
12+
# Example 1:
13+
# Input: flowerbed = [1,0,0,0,1], n = 1
14+
# Output: True
15+
# Example 2:
16+
# Input: flowerbed = [1,0,0,0,1], n = 2
17+
# Output: False
18+
# Note:
19+
# The input array won't violate no-adjacent-flowers rule.
20+
# The input array size is in the range of [1, 20000].
21+
# n is a non-negative integer which won't exceed the input array size.
22+
23+
class Solution(object):
24+
def canPlaceFlowers(self, flowerbed, n):
25+
"""
26+
:type flowerbed: List[int]
27+
:type n: int
28+
:rtype: bool
29+
"""
30+
for i in xrange(len(flowerbed)):
31+
if flowerbed[i] == 0 and (i == 0 or flowerbed[i-1] == 0) and \
32+
(i == len(flowerbed)-1 or flowerbed[i+1] == 0):
33+
flowerbed[i] = 1
34+
n -= 1
35+
if n <= 0:
36+
return True
37+
return False

0 commit comments

Comments
 (0)