Skip to content

Commit b7b4eaa

Browse files
committed
✨ leetcode 第605题
1 parent 7c67e32 commit b7b4eaa

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.fuyd.other;
2+
3+
/**
4+
* 假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
5+
*
6+
* 给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。
7+
*
8+
* 示例 1:
9+
*
10+
* 输入: flowerbed = [1,0,0,0,1], n = 1
11+
* 输出: True
12+
* 示例 2:
13+
*
14+
* 输入: flowerbed = [1,0,0,0,1], n = 2
15+
* 输出: False
16+
* 注意:
17+
*
18+
* 数组内已种好的花不会违反种植规则。
19+
* 输入的数组长度范围为 [1, 20000]。
20+
* n 是非负整数,且不会超过输入数组的大小。
21+
*
22+
* 来源:力扣(LeetCode)
23+
* 链接:https://leetcode-cn.com/problems/can-place-flowers
24+
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
25+
*
26+
* @author fuyongde
27+
* @date 2020/2/28 22:22
28+
*/
29+
public class Solution605 {
30+
31+
/**
32+
* 贪心算法
33+
* 从左到右扫描数组,如果数组中有一个0,并且这个0的左右两侧都是0,则这个位置可以种花,
34+
* 并将该位置置为1,针对计数增加1,当计数 >= n 时,则为 true,否则为 false
35+
* 时间复杂度:O(n),可以在循环中,增加计数与 n 的判断,来减少循环的次数,从而使程序执行效率更高
36+
* 空间复杂度:O(1)
37+
*/
38+
public boolean canPlaceFlowers(int[] flowerbed, int n) {
39+
int i = 0, count = 0;
40+
while (i < flowerbed.length) {
41+
if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
42+
flowerbed[i] = 1;
43+
count++;
44+
}
45+
i++;
46+
}
47+
return count >= n;
48+
}
49+
}

0 commit comments

Comments
 (0)