605. 种花问题

605. 种花问题

leetcode 605. 种花问题


题目:605. 种花问题

假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。

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

示例1:

输入: flowerbed = [1,0,0,0,1], n = 1
输出: True

示例2:

输入: flowerbed = [1,0,0,0,1], n = 2
输出: False

提示:

  1. 数组内已种好的花不会违反种植规则。
  2. 输入的数组长度范围为 [1, 20000]。
  3. n 是非负整数,且不会超过输入数组的大小。

方法:贪心

思路:从头开始一个一个判断是否可以种植花卉。

运行数据:执行用时:1 ms,内存消耗:41.5 MB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// LeetCode指定调用方法
public boolean canPlaceFlowers(int[] flowerbed, int n) {

int len = flowerbed.length;

for (int i = 0; i < len; i++) {
if (flowerbed[i] == 1) continue;
int pre = i == 0 ? 0 : flowerbed[i - 1];
int next = i == len - 1 ? 0 : flowerbed[i + 1];
if (pre == 0 && next == 0) {
flowerbed[i] = 1;
n--;
}
}

return n <= 0;
}

学习所得,资料、图片部分来源于网络,如有侵权,请联系本人删除。

才疏学浅,若有错误或不当之处,可批评指正,还请见谅!


 
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×