605. Can Place Flowers
2018-03-26 10:16
330 查看
Suppose 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 - they would compete for water and both would die.Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.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
Note:
The input array won't violate no-adjacent-flowers rule.
The input array size is in the range of [1, 20000].
n is a non-negative integer which won't exceed the input array size.
解题思路:
这道题主要是找到连续的0的数量,然后根据0的数量来判断可以放多少朵花,然后注意!起始部位连续的0和结尾连续的0的情况一定要考虑进去!!!
解题代码:
ans=0
cnt=1
for flower in flowerbed:
if flower == 0:
cnt +=1
else:
ans += abs(cnt-1)//2
cnt=0
return ans+cnt/2>=n
Input: flowerbed = [1,0,0,0,1], n = 1
Output: True
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: False
Note:
The input array won't violate no-adjacent-flowers rule.
The input array size is in the range of [1, 20000].
n is a non-negative integer which won't exceed the input array size.
解题思路:
这道题主要是找到连续的0的数量,然后根据0的数量来判断可以放多少朵花,然后注意!起始部位连续的0和结尾连续的0的情况一定要考虑进去!!!
解题代码:
ans=0
cnt=1
for flower in flowerbed:
if flower == 0:
cnt +=1
else:
ans += abs(cnt-1)//2
cnt=0
return ans+cnt/2>=n
相关文章推荐
- leetcode -- 605. Can Place Flowers 【边界处理 + 数学规律】
- Leetcode 605. Can Place Flowers(Easy)
- LeetCode 605.Can Place Flowers
- [leetcode]: 605. Can Place Flowers
- 605. Can Place Flowers
- LeetCode 605. Can Place Flowers
- Leetcode 605 Can Place Flowers
- LeetCode-605. Can Place Flowers
- 【LeetCode】605. Can Place Flowers 解题报告
- leetcode 605. Can Place Flowers python
- [LeetCode]605. Can Place Flowers
- 605. Can Place Flowers
- leetcode 605[easy]---Can Place Flowers
- [Leetcode] 605. Can Place Flowers 解题报告
- LeetCode: 605. Can Place Flowers
- 605. Can Place Flowers
- 【leetcode】605. Can Place Flowers(Python & C++)
- LeetCode 605. Can Place Flowers
- leet code 605 Can Place Flowers
- LeetCode-605:Can Place Flowers (可放置花的数量)