您的位置:首页 > 其它

605. Can Place Flowers

2018-01-11 10:38 351 查看
1. Description

Given an array only consisting of 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 adjacent flowers.

2. Solution

把前后两端填入0,然后找到数组中所有是0,且前后均为0的位置,把这个位置变成1,并计数。

如果计数结果大于或等于n,返回true。

3. Code

bool canPlaceFlowers(vector<int>& flowerbed, int n) {
flowerbed.insert(flowerbed.begin(),0);
flowerbed.push_back(0);
int m = flowerbed.size();
int ans=0;
for(int i=1;i<m-1;i++){
if(flowerbed[i]==0){
if(flowerbed[i-1]==0&&flowerbed[i+1]==0){
flowerbed[i]=1;
ans++;
}
}
}
if(ans>=n)
return true;
else
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Array