LeetCode //C - 605. Can Place Flowers

2023-12-15 08:28:34

605. Can Place Flowers

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 true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.
?

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 < = f l o w e r b e d . l e n g t h < = 2 ? 1 0 4 1 <= flowerbed.length <= 2 * 10^4 1<=flowerbed.length<=2?104
  • flowerbed[i] is 0 or 1.
  • There are no two adjacent flowers in flowerbed.
  • 0 <= n <= flowerbed.length

From: LeetCode
Link: 605. Can Place Flowers


Solution:

Ideas:
  • We iterate over each plot in the flowerbed.
  • We check if the current plot is empty and its adjacent plots are also empty (or the plot is at the boundary of the flowerbed).
  • If we can plant a flower, we set flowerbed[i] to 1 and decrement n.
  • After the loop, we check if n has reached 0, indicating that all required flowers have been planted.
Code:
bool canPlaceFlowers(int* flowerbed, int flowerbedSize, int n) {
    for (int i = 0; i < flowerbedSize && n > 0; i++) {
        // Check if current plot is empty and adjacent plots are also empty (or non-existent)
        if (flowerbed[i] == 0) {
            bool emptyLeft = (i == 0) || (flowerbed[i - 1] == 0);
            bool emptyRight = (i == flowerbedSize - 1) || (flowerbed[i + 1] == 0);

            if (emptyLeft && emptyRight) {
                flowerbed[i] = 1; // Plant a flower
                n--; // Decrease the number of flowers needed
            }
        }
    }
    return n == 0; // Return true if all flowers can be planted, otherwise false
}

文章来源:https://blog.csdn.net/navicheung/article/details/135007928
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。