Preface explains

Algorithm learning, daily brush problem record.

Subject to connect

Problems and flowers

The subject content

Suppose you have a very long flower bed, and one part of the plot is planted with flowers, and another part is not. But flowers can’t be planted on adjacent plots. They will compete for water, and both will die.

I give you an integer array flowerbed for a flowerbed, consisting of 0s and 1s, where 0 means no flowers and 1 means flowers are planted. If I have another number n, can I plant n flowers without breaking the planting rules? Return true if it is, false if it is not.

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

Tip:

1 <= flowerbed.length <= 2 * 10^4

Flowerbed [I] is 0 or 1

There are no two adjacent flowers in a Flowerbed

0 <= n <= flowerbed.length

The analysis process

Walk through the array of flower beds in three cases.

In the first case, in the first position, if the array is larger than 1 and no flowers are planted in the next position, then this position is changed to 1, marked as planting flowers, and the number of flowers planted is increased by 1.

In the second case, in the last position, if no flowers were planted in the previous position of the flowerbed array, this position is changed to 1, marked as planting flowers, and the number of flowers planted is increased by 1.

In the third case, in the middle position, if there are no flowers in either the first or the second position of the flowerbed array, this position is changed to 1, marked as planting flowers, and the number of flowers planted is increased by 1.

If the number of flowers is greater than n, return true; if the number is less than n, return false.

To solve the code

So the solution code is:

Class Solution {public Boolean canplacefflowers (int[] flowerbed, int n) { Int size = flowerbed.length; For (int I = 0; i < size; ++i) { int flower = flowerbed[i]; If (flower == 0) {if (I == 0) {if (size > 1 && flowerbed[I + 1] == 0) {if (size > 1 && flowerbed[I + 1] == 0) { Change this element to 1 flowerBed [I] = 1; // Add 1 ++num; } else if (size <= 1) {// Add 1 ++num; Flowerbed [I] = 1; flowerbed[I] = 1; flowerbed[I] = 1; flowerbed[I] = 1; // Add 1 ++num; } else {if (flowerbed[I - 1] == 0 && flowerbed[I + 1] == 0) {else {if (flowerbed[I - 1] == 0 && flowerbed[I + 1] == 0) { Change this element to 1 flowerBed [I] = 1; // Add 1 ++num; }} if (num >= n) {return true; } // Return true if num >= n; // Return false if num >= n; }}Copy the code

Submit the results

It took 1ms to execute, beating 99.98% of users in time, 39.9MB in memory and 54.94% in space.

The original link

The question of planting flowers