[LeetCode] 605. Can Place Flowers

Suppose 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 - they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it 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

Note:

  1. The input array won't violate no-adjacent-flowers rule.
  2. The input array size is in the range of [1, 20000].
  3. n is a non-negative integer which won't exceed the input array size.

种花问题。

题意是给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。

思路是去遍历这个数组,判断每个位置上是否能种花,除了判断当前位置是否已经种花了以外,还需要判断这个位置的前一个和后一个位置上是否有种花。对于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 };

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12610108.html