【贪心算法】3、种花问题(easy)

在这里插入图片描述
看题目就很容易想到利用贪心来解题。
为了在现有地块中种上更多的花,所以贪心策略为只要有符合种花条件的地块,就在该地块上种花。所以遍历所有地块,看最多能种的花是否大于等于要种的花。

判断地块 i i i是否能种花需要判断三处:
当前地块 i i i,地块 i − 1 i-1 i1,地块 i + 1 i+1 i+1,一般情况下,这三块地块的值需均为0(未种花状态)

flowerbed[i]==0 && flowerbed[i-1]==0  && flowerbed[i+1]==0 

特殊情况:

  • i = = 0 i==0 i==0时,只需要判断地块 i i i和地块 i + 1 i+1 i+1是否未种花
flowerbed[i]==0 && flowerbed[i+1]==0  && i== 0
  • i = = l e n g t h − 1 i==length-1 i==length1时,只需要判断地块 i i i和地块 i − 1 i-1 i1是否未种花
flowerbed[i]==0 && flowerbed[i-1]==0  && i== flowerbed.length-1

code:

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int num = flowerbed.length;
        if(num==0) return false;
        int count=0;//记录种花的数量
        for(int i=0;i<num;i++){
            if(flowerbed[i]==0 && (i==0||flowerbed[i-1]==0) && (i==num-1 || flowerbed[i+1]==0)){
                flowerbed[i]=1;//种上花
                count++;
            }
        }
        return count>=n?true:false;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值