Skip to content

Commit 0233dcd

Browse files
committed
add: 605. 种花问题
1 parent 9c82d50 commit 0233dcd

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,7 @@
294294
- [x] [455.分发饼干](./topics/greedy/ext-assign-cookies.md)
295295
- [x] [976.三角形的最大周长](./topics/greedy/ext-largest-perimeter-triangle.md)
296296
- [x] [435.无重叠区间](./topics/greedy/ext-non-overlapping-intervals.md)
297+
- [x] [605.种花问题](./topics/greedy/ext-can-place-flowers.md)
297298

298299
## 其他
299300

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# 605. 种花问题
2+
3+
https://leetcode-cn.com/problems/can-place-flowers/
4+
5+
## 题目描述
6+
7+
```
8+
假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
9+
10+
给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。
11+
12+
示例 1:
13+
14+
输入: flowerbed = [1,0,0,0,1], n = 1
15+
输出: True
16+
示例 2:
17+
18+
输入: flowerbed = [1,0,0,0,1], n = 2
19+
输出: False
20+
注意:
21+
22+
数组内已种好的花不会违反种植规则。
23+
输入的数组长度范围为 [1, 20000]。
24+
n 是非负整数,且不会超过输入数组的大小。
25+
26+
来源:力扣(LeetCode)
27+
链接:https://leetcode-cn.com/problems/can-place-flowers
28+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
29+
```
30+
31+
## 方法 1: 贪心
32+
33+
### 思路
34+
35+
如果有一个 `0` 坑,并且它旁边两个坑都是 `0`,那我们就可以种下一朵花。
36+
37+
需要能种至少 n 朵花,贪心策略很简单:就是遇到一个能种花的坑就把花种下,然后继续去找下一个坑。如果种完了 n 朵花就可以提前返回结果了。
38+
39+
### 复杂度分析
40+
41+
- 时间复杂度:$O(N)$,N 为数组长度。
42+
- 空间复杂度:$O(1)$。
43+
44+
### 代码
45+
46+
JavaScript Code
47+
48+
```js
49+
/**
50+
* @param {number[]} flowerbed
51+
* @param {number} n
52+
* @return {boolean}
53+
*/
54+
var canPlaceFlowers = function (flowerbed, n) {
55+
let i = 0;
56+
57+
while (i < flowerbed.length) {
58+
// 如果找到一个 0,并且它前后都是 0,就可以种一朵花
59+
if (!flowerbed[i] && !flowerbed[i - 1] && !flowerbed[i + 1]) {
60+
n--;
61+
// 因为它旁边不能再种花了,所以 i+=2 跳过一个坑
62+
i += 2;
63+
} else {
64+
i++;
65+
}
66+
if (n <= 0) return true;
67+
}
68+
69+
return false;
70+
};
71+
```
72+
73+
更多题解可以访问:[https://github.com/suukii/91-days-algorithm](https://github.com/suukii/91-days-algorithm)

0 commit comments

Comments
 (0)