No.260 - LeetCode[605] Can Place Flowers - 非常有意思的一道数组相邻题

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分为三块:
左侧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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值