题目
假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给你一个整数数组 flowerbed
表示花坛,由若干 0
和 1
组成,其中 0
表示没种植花,1
表示种植了花。另有一个数 n
,能否在不打破种植规则的情况下种入 n
朵花?能则返回 true
,不能则返回 false
。
示例 1:
输入:flowerbed = [1,0,0,0,1], n = 1
输出:true
示例 2:
输入:flowerbed = [1,0,0,0,1], n = 2
输出:false
提示:
1 <= flowerbed.length <= 2 * 104
flowerbed[i]
为0
或1
flowerbed
中不存在相邻的两朵花0 <= n <= flowerbed.length
思路
- 顺序遍历,只要相邻的位置没有1,则直接插入,若是插够了直接返回true,若是插满了还有剩直接返回false。
代码实现
cpp
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int length = flowerbed.size(), pre = 0, now = 0, next = 1;
if(n == 0) return true;
if(length == 1) {
if(flowerbed[0] == 1) return false;
else return true;
}
for(now = 0; now < length; now++) {
// 这里我还试了三个数相加等于0这种判断方法,显著性地时间开销变大了,猜测是因为需要额外分配空间存放累加结果,而相加和判断相等也是涉及三次操作,所以额外的分配空间的过程就会浪费掉时间了。
if(flowerbed[pre]==0 && flowerbed[now]==0 && flowerbed[next]==0) {
flowerbed[now] = 1;
n--;
if(n == 0) return true;
}
if(pre!=now) pre++;
if(next != length-1) next++;
}
return false;
}
};
复杂度分析
- 时间复杂度:总共只涉及一次遍历,时间复杂度为O(n)。
- 空间复杂度:O(1)。
官方题解
- 好的,谢谢官方题解,都忘记这个方法属于贪心算法了。------因为如果两个1之间可以种花,那早点种是不会影响剩下的空间的种花的(具体的分析请看leetcode的题解),所以可以贪心的能种就种。