分为三块:
左侧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
这是一个关于计算机算法的问题,具体是LeetCode上的第605题《CanPlaceFlowers》。代码实现了一个C++类Solution,该类包含一个公共成员函数`canPlaceFlowers`,用于判断在给定的flowerbed数组中是否能种植n朵花。函数首先计算数组两侧0的个数,然后在数组中间寻找可以种植的位置,最后根据条件判断能否种植至少n朵花。
243

被折叠的 条评论
为什么被折叠?



