leetcode 605.种花问题(java 贪心)

https://leetcode-cn.com/problems/can-place-flowers/

给定01序列,每两个1之间必须有0,问是否能插入n个1在这个序列中。

模拟即可,设定两个变量pre和next,表示当前指定的flowerbed[i]的前一个和后一个是否是0,从而判断能否插入1,这样做很巧妙,当i=0时,pre=0;当i=len-1时,next=0。

注意:做的时候没想到可以直接用pre和next两个变量,这样可以直接方便的解决首尾问题。

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int sum=0;
        int len=flowerbed.length;
        for(int i=0;i<len&&sum<n;i++){
            if(flowerbed[i]==1){
                continue;
            }
            int pre= i==0 ? 0: flowerbed[i-1];
            int next= i==len-1 ? 0 : flowerbed[i+1];
            if(pre==0&&next==0){
                sum++;
                flowerbed[i]=1;
            }
        }
        return sum>=n;
    }
}
原文地址:https://www.cnblogs.com/y1040511302/p/11521970.html