LeetCode 605. Can Place Flowers (可以种花)
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.
题目标签:Array
题目给了我们一个 flowerbed array, 和一个 n, 让我们找出是否右足够的空间来置放 n 个花。 每一朵符合条件的花,它的左右相邻位置 不能有花。
所以我们要遍历flowerbed array:
如果遇到0的话,还要检查这个0的左右两边是否都是0,都是0的情况下,才可以算作一个空间来置放花,然后可以额外跳过右边的0;
如果遇到1的话,只需要额外跳过1右边的位置;
一旦当空间数量 已经 等于 n 了,就不需要继续找下去了,直接返回true。(这里要加一个 = ,因为给的 n 有可能是 0)
当遍历完了,说明空间不够,返回 false 即可。
Java Solution:
Runtime beats 60.45%
完成日期:10/15/2017
关键词:Array
关键点:符合条件的empty spot 的 左右邻居也要为0
class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { int count = 0; // count the valid empty spot for(int i=0; i<flowerbed.length; i++) { if(flowerbed[i] == 0) // if find empty spot, check its adjacent spots { if(i-1 >= 0 && flowerbed[i-1] == 1) // check left adjacent spot continue; if(i+1 < flowerbed.length && flowerbed[i+1] == 1) // check right adjacent spot continue; // if come here, meaning this 0 is valid spot to place flower count++; i++; // skip next 0 } else if(flowerbed[i] == 1) // if find a flower spot, its next spot is not valid, skip it { i++; } if(count >= n) // if there are enough spots to place flower, no need to continue return true; } return false; } }
参考资料:N/A
LeetCode 题目列表 - LeetCode Questions List
- 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 解题报告
- 【leetcode】605. Can Place Flowers(Python & C++)
- leetcode 605. Can Place Flowers python
- 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
- 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(Easy)
- leetcode 605. Can Place Flowers
- [LeetCode]605. Can Place Flowers
- LeetCode@Array_605_Can_Place_Flowers