本文主要是介绍LeetCode //C - 605. Can Place Flowers,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 flowern--; // Decrease the number of flowers needed}}}return n == 0; // Return true if all flowers can be planted, otherwise false
}
这篇关于LeetCode //C - 605. Can Place Flowers的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!