2020-02-06
1.题目描述
给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。
返回能否在不打破种植规则的情况下种入 n 朵花
2.题解
直接从左往右按照规则进行种植即可,注意种植后要进行赋值
3.代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int s=0,l=flowerbed.size();
for (int i=0;i<l;i++){
if ((!flowerbed[i])&&(i-1<0||!flowerbed[i-1])&&(i+1>=l||!flowerbed[i+1])){
s++;
flowerbed[i]=1;
}
}
if (s>=n) return true;
return false;
}
};
int main(){
Solution s;
int a[6]={1,0,0,0,0,1};
vector<int>v(a,a+6);
cout<<s.canPlaceFlowers(v,2);
return 0;
}