leetcode_打卡04

leetcode_打卡04

题目:605. 种花问题

解答:

三种情况:

  1. 第一个1的左边全是0的情况,此时 可以插入的位置为result=(i-1+1)/2 ,如【0,0,0,1,0,0,1】
  2. 两个1之间全是0的情况。此时 可以插入的位置为result=(i-flag-1-2+1)/2
  3. 第一个1的右边全是0的情况,此时 可以插入的位置为result=(count-flag-2+1)/2 ,如【0,0,0,1,0,0,1】

注意: 两边都有1时需要 -2

​ 单边的时候 -1

代码:

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int count = flowerbed.length;
        int flag=-1; 
        int i=0,result=0;
        for(i=0;i<count;i++){
            if(flowerbed[i]==1){
                if(flag<0){
                    result+=(i)/2;    //情况1
                }else{
                    result=result+(i-flag-2)/2;  // 情况2
                }
                flag=i;
                
            }
        }
        
       if(flag<0){
           result=result+(count+1)/2;  // 数组只有一个元素的情况
       }else{
           result=result+(i-flag-1)/2;  //情况3
       }

       return result>=n;
        
    }
}
posted @ 2023-04-14 21:07  ZLey  阅读(7)  评论(0编辑  收藏  举报