LeetCode
假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给你一个整数数组 flowerbed 表示花坛,由若干 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 <= flowerbed.length <= 2 * 104
flowerbed[i] 为 0 或 1
flowerbed 中不存在相邻的两朵花
0 <= n <= flowerbed.length
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/can-place-flowers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
贪心法,模拟种花的过程,能种就种。
时间复杂度:O(N)
空间复杂度:O(1)
class Solution(object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
for i, x in enumerate(flowerbed):
if not x:
if (i - 1 < 0 or flowerbed[i - 1] == 0) and (i + 1 == len(flowerbed) or flowerbed[i + 1] == 0):
flowerbed[i] = 1
n -= 1
return n <= 0
相关知识
LeetCode
力扣题目训练:605
力扣 leetcode 605. 种花问题 (python)
Leetcode刷题笔记 605. 种花问题
原文链接: LeetCode https://www.huajiangbk.com/newsview3155.html
| 上一篇: 保定街头花团锦簇!200万盆鲜花... | 下一篇: 专题 |
推荐分享

- 1胡椒木盆景从上盆制作到养护,... 53957
- 2明日花キララ:明日花绮罗年度... 48914
- 3明日花キララ(明日花绮罗)经... 27886
- 4五月天婷婷开心六月丁香:音乐... 18764
- 5仙人球“水蜜桃”—又美又仙,... 16946
- 6十大致癌花卉排行榜,哪些花卉... 16303
- 7超简单,3个步骤带你学会毛线... 16029
- 8兰花叶子扭的是什么兰 15130
- 9老师精选05—河北彩花(出道... 13976
- 10家庭养花知识大全 家庭养花有... 11545




