假设你有一个长花圃,其中有些地块已经被种植了,但是有些地块没有。但是,花不能够在相邻的地块下种植 - 他们会争夺水从而导致两者的死亡。
给定一个花圃(用一个包含0和1的数组来表示,其中0代表空,1代表非空),和一个数字n,返回n朵新的花在这个花圃上以能否在不违反“无相邻花”的规则种植。
样例1
输入: flowerbed = [1,0,0,0,1], n = 1
输出: True
样例2
输入: flowerbed = [1,0,0,0,1], n = 2
输出: False
class Solution {
public:
/**
* @param flowerbed: an array
* @param n: an Integer
* @return: if n new flowers can be planted in it without violating the no-adjacent-flowers rule
*/
bool canPlaceFlowers(vector<int> &flowerbed, int n) {
// Write your code here
flowerbed.insert(flowerbed.begin(),0);
flowerbed.push_back(0);
int len=flowerbed.size();
for (int i = 1; i < len; i++) {
/* code */
if(flowerbed[i-1]==0&&flowerbed[i]==0&&flowerbed[i+1]==0){flowerbed[i]=1; count++;}
if(count>=n) {return true;break;}
}
return false;
}
int count=0;
};