LeetCode 605. Can Place Flowers(种植花朵)

题目描述:flowerbed 数组中 1 表示已经种下了花朵。花朵之间至少需要一个单位的间隔,求解是否能种下 n 朵花。

有两种情况可种花:

  1. 000
  2. 001/ 100
  public boolean canPlaceFlowers(int[] flowerbed, int n) {
        if(flowerbed.length == 0) return false;

        //能种花的数量
        int count = 0;
        for(int i = 0; i < flowerbed.length; i ++) {
            if(flowerbed[i] == 0 
            && (i == 0 || flowerbed[i - 1] == 0)
            && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
                
                flowerbed[i] = 1;
                count ++;
            }

            if(count >= n) return true; 
        }

        return false;
    }
发布了581 篇原创文章 · 获赞 97 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/gx17864373822/article/details/104900359