[LeetCode] 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 <= flowerbed.length <= 2 * 104
flowerbed[i]
is0
or1
.- There are no two adjacent flowers in
flowerbed
. 0 <= n <= flowerbed.length
种花问题。
假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给你一个整数数组 flowerbed 表示花坛,由若干 0 和 1 组成,其中 0 表示没种植花,1 表示种植了花。另有一个数 n ,能否在不打破种植规则的情况下种入 n 朵花?能则返回 true ,不能则返回 false 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/can-place-flowers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是贪心。具体做法是去遍历这个数组,判断每个位置上是否能种花,除了判断当前位置是否已经种花了以外,还需要判断这个位置的前一个和后一个位置上是否有种花。对于 input 的第一个位置和最后一个位置需要特判,如果是第一个位置。最后判断能种的花的数量是否大于等于 n。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public boolean canPlaceFlowers(int[] flowerbed, int n) { 3 for (int i = 0; i < flowerbed.length; i++) { 4 if (flowerbed[i] == 0 && (i - 1 == -1 || flowerbed[i - 1] == 0) 5 && (i + 1 == flowerbed.length || flowerbed[i + 1] == 0)) { 6 n--; 7 flowerbed[i] = 1; 8 } 9 } 10 return n <= 0; 11 } 12 }
JavaScript实现
1 /** 2 * @param {number[]} flowerbed 3 * @param {number} n 4 * @return {boolean} 5 */ 6 var canPlaceFlowers = function(flowerbed, n) { 7 let len = flowerbed.length; 8 for (let i = 0; i < len; i++) { 9 if ( 10 flowerbed[i] == 0 && 11 (i - 1 == -1 || flowerbed[i - 1] == 0) && 12 (i + 1 == len || flowerbed[i + 1] == 0) 13 ) { 14 n--; 15 flowerbed[i] = 1; 16 } 17 } 18 return n <= 0; 19 };