605. Can Place Flowers[easy]

605. Can Place Flowers

Title description

Suppose there is a very long flower bed, one part of the plot is planted with flowers, and the other part is not. However, flowers cannot be planted on adjacent plots, they will compete for water, and both will die.

Give you an integer array flowerbed that represents the flowerbed, which is composed of a number of 0 and 1, where 0 means no flowers are planted, and 1 means flowers are planted. There is another number n. Can n flowers be planted without breaking the planting rules? It returns true if it can, and false if it can't.

Example 1:

输入:flowerbed = [1,0,0,0,1], n = 1
输出:true

Example 2:

输入:flowerbed = [1,0,0,0,1], n = 2
输出:false

prompt:

1 <= flowerbed.length <= 2 * 104
flowerbed[i] 为 0 或 1
flowerbed 中不存在相邻的两朵花
0 <= n <= flowerbed.length

answer

Positioning: Greedy problem to solve the maximum number
of flowers planted in the flowerbed Sub-problem: solve the length of each 0 interval and calculate the number of flowers that can be planted in the subinterval according to the interval length

Mathematics induction:

  • For the middle 0 interval:

    • 1~2 0: 0 can be planted;

    • 3~4: 1 can be planted;

    • 5~6: 2 can be planted;

    • count: can be planted (count-1)/2 flowers

  • For the 0 interval at both ends, since there is no restriction of 1 on the left and right, the number of flowers that can be planted is slightly different
    + You can add 1 0 to the left and right of the array, which means there are no flowers on the left and right of the flower bed.

Code

class Solution {
    
    
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
    
    
        // 贪心问题 求解花坛的最大种花数量
        //  根据花坛中0的个数来计算
        // 数学归纳:
        // 1-2 0
        // 3-4 1
        // 5-6 2
        // count = (count-1)/2
        // 优化
        if(flowerbed.length==0 || flowerbed == null ){
    
    
            return n==0;
        }
        // 统计可以种花数目
        int num = 0;
        // 花坛总长度
        // 计算0的个数 默认为1可以处理边界问题 补00操作
        int countofzero = 1;
        int length = flowerbed.length;
        for(int i=0;i<length;i++){
    
    
            if(flowerbed[i] == 0){
    
    
                countofzero++;
            }else{
    
    
                //遇到1了 计算该区间种花的个数
                num += (countofzero-1)/2;
                countofzero = 0 ;
            }

        }
        // 最后补0
        countofzero++;
        num += (countofzero-1)/2;
        return num>=n;
    }
}

Guess you like

Origin blog.csdn.net/qq_37747189/article/details/115112782