基本思想:
注意特例,首尾添0最可靠;
具体代码:
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int cnt = 0;
int index = 0;
flowerbed.insert(flowerbed.begin(),0);
flowerbed.push_back(0);
for (int i = 0; i < flowerbed.size(); i++) {
if (flowerbed[i] == 1) {
cnt += int((i - index - 1) / 2);
index=i+1;
}
}
if(index<flowerbed.size()){
cnt += int((flowerbed.size() - index - 1) / 2);
}
if (n > cnt)
return false;
else
return true;
}
};