分为三块:
左侧0个数
右侧0个数
中间0个数
在最后判断一下数组中是否有1
/*
* @lc app=leetcode id=605 lang=cpp
*
* [605] Can Place Flowers
*/
// @lc code=start
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int N = flowerbed.size();
int L = 0;
int R = 0;
for(int i=0;i<N;i++){
if(flowerbed[i] == 0) L++;
else break;
}
for(int i=N-1;i>=0;i--){
if(flowerbed[i] == 0) R++;
else break;
}
int cnt = 0;
int loc = L;
int ans = 0;
bool hasOne = false;
while( loc < N-R ){
if( flowerbed[loc] == 0 ){
cnt = 0;
while( flowerbed[loc] == 0 && loc < N-R){
loc ++ ;
cnt ++ ;
}
ans += (cnt-1) / 2 ;
}else{
hasOne = true;
}
loc++;
}
//printf("%d,%d,%d\n",L,R,ans);
if(hasOne){
ans += L/2 + R/2;
}else{
ans += (L+1)/2;
}
return ans >= n ;
}
};
// @lc code=end