【LeetCode】605. Can Place Flowers (Easy) (JAVA) One question per day

【LeetCode】605. Can Place Flowers (Easy) (JAVA)

Subject address: https://leetcode.com/problems/can-place-flowers/

Title description:

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.

Given an integer array flowerbed containing 0’s and 1’s, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.

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

Constraints:

  • 1 <= flowerbed.length <= 2 * 10^4
  • flowerbed[i] is 0 or 1.
  • There are no two adjacent flowers in flowerbed.
  • 0 <= n <= flowerbed.length

General idea

Suppose you have a very long flower bed, and one part of the plot is planted with flowers but another 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.

Problem-solving method

  1. Using greedy algorithm, when encountering 0, as long as the current i = 0 or flowered[i-1] = 0, set the current element to 1, and n-1
  2. If flowerbed[i] == 1, and the previous flowerbed[i-1] == 1, it means that the previous placement of 1 failed, and you need to add back n + 1
  3. Until n is 0
class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        if (n <= 0) return true;
        for (int i = 0;i < flowerbed.length; i++) {
            if (flowerbed[i] == 1) {
                if (i > 0 && flowerbed[i - 1] == 1) n++;
            } else {
                if (i == 0 || (i > 0 && flowerbed[i - 1] == 0)) {
                    n--;
                    flowerbed[i] = 1;
                }
            }
            if (n == 0 && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) return true;
        }
        return false;
    }
}

Execution time: 1 ms, beating 100.00% of Java users
Memory consumption: 40.2 MB, beating 21.04% of Java users

Welcome to pay attention to my official account, LeetCode updates one question every day

Guess you like

Origin blog.csdn.net/qq_16927853/article/details/112058437