Question
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、1数组,0表示空,1表示非空,给定整数n,判断是否可以插入n个1,1不能相邻。
Answer
Solution 1:
简单分情况考虑。
- 题目看似情况不多,在实际编写过程中还是发现容易忽略很多情况。
- 首先考虑插入的规则:num个连0,则表示可以插入
(num-1)/2个1; - 再考虑首尾元素是零的情况,当首位是0或者末位是0,那么只要有两个0则便可以插入1个
1,也就是说,首位和末位的一个0可以当做两个0来使用; - 最后考虑还有一种情况是,数组为一个0的情况,这个时候可以插入1个
1; - 连续0结束则计算一次剩余需要插入的1的个数。
- 解法直观,但是没有新意,也容易考虑不周出错。
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = 0;
if (flowerbed == null || flowerbed.length == 0) return false;
if (flowerbed.length == 1 && flowerbed[0] == 0) return true;
for (int i = 0; i < flowerbed.length && n > 0; i++){
if (flowerbed[i] == 0){
if (i == 0 || i == flowerbed.length-1) count++;
count++;
}else{
n -= (count-1)/2;
count = 0;
}
}
n -= (count-1)/2;
return n < 1;
}
}
- 时间复杂度:O(n),空间复杂度:O(1)
Solution 2:
使用贪心算法。
- 使用贪心的思想去解决,即只要位置满足条件就立即插入1,直到
n == 0或者数组遍历完毕。 - 同时需要考虑首位和末位是零的情况。
- 判断条件即判断左右两边分别均是0,只要插入了位置该位置则置1.
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
for (int idx = 0; idx < flowerbed.length && n > 0; idx ++)
if (flowerbed[idx]==0 && (idx==0 || flowerbed[idx-1]==0) &&
(idx==flowerbed.length-1 || flowerbed[idx+1]==0)){
n--;
flowerbed [idx] = 1;
}
return n == 0;
}
}
- 时间复杂度:O(n),空间复杂度:O(1)

探讨如何在遵循不相邻种花规则下,确定能否在给定的花坛中种植指定数量的花朵。通过两种方法实现——一种是直接计算可种植花朵的数量,另一种采用贪心算法逐个尝试种植。
1758

被折叠的 条评论
为什么被折叠?



