Flower problem java

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

Given a flower bed (represented as an array containing 0 and 1, where 0 means no flowers are planted, and 1 means flowers are planted), and a 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:

Input: flowerbed = [1,0,0,0,1], n = 1
Output: True
Example 2:

Input: flowerbed = [1,0,0,0,1], n = 2
Output: False
Note:

The flowers already planted in the array will not violate the planting rules.
The input array length range is [1, 20000].
n is a non-negative integer and will not exceed the size of the input array.

Source: LeetCode
Link: https://leetcode-cn.com/problems/can-place-flowers
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

ps: Although it is a simple question, the code written in the first place can actually be improved in many ways.
pps: I'm really an idiot. You don't need to check the array, just change it directly on the original array, and use 0,1 to judge, saving a round of time.

class Solution {
    
    
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
    
    
        int len = flowerbed.length;
        if(len==1)
        {
    
    
            int count = flowerbed[0]==0?1:0;
            return count>=n?true:false;
        }
        boolean[] check = new boolean[len];
        for(int i=0;i<len;i++)//有花为true,无花为false
        {
    
    
            if(flowerbed[i]==1)//boolean数组默认为false
            {
    
    
                check[i] = true;
            }
        }
        int count = 0;
        if(check[0]==false && check[1]==false)
        {
    
    
            count++;
            check[0] = true;
        }
        for(int i=1;i<len-1;i++)
        {
    
    
            //改进的点!!!!if在这里就是2ms,在里面就是1ms,这里的差距是十分大的
            //if(count>=n)
                   // break;
            if(check[i-1]==false && check[i+1]==false && check[i]==false)//左右包括自己都没有花,那就可以种花了
            {
    
    
                count++;
                check[i] = true;
                if(count>=n)//人傻了,这里要什么break,直接返回true就行了
                    return true;
            }
        }
        if(check[len-1]==false && check[len-2]==false)
            count++;
        return count>=n?true:false;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43824233/article/details/112060357