[leetcode]605. Can Place Flowers
Analysis
ummm~—— [ummmm~]
Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.
Given a flowerbed (represented as an array containing 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 violating the no-adjacent-flowers rule.
遍历数组,如果某个元素为‘0’,并且其左右元素均为‘0’,则可以种一棵花,(如果该元素是数组的第一个元素,则只要其后一个元素为‘0’即可;若该元素是数组的最后一个元素,则只要其前一个元素为‘0’即可)如果最后所有花都没种下了,则返回true。
Implement
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int len = flowerbed.size();
for(int i=0; i<len; i++){
if(n == 0)
break;
if(flowerbed[i] == 0){
if(i == 0 && flowerbed[i+1] == 0){
n--;
flowerbed[i] = 1;
}
else if(i == len-1 && flowerbed[i-1] == 0){
n--;
flowerbed[i] = 1;
}
else if(flowerbed[i-1]==0 && flowerbed[i+1] == 0){
n--;
flowerbed[i] = 1;
}
}
}
if(n == 0)
return true;
return false;
}
};