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

分为三块:
左侧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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值