python-leetcode-种花问题

605. 种花问题 - 力扣(LeetCode)

使用 贪心算法 来解决这个问题,思路如下:

  1. 遍历 flowerbed 数组,找到值为 0 的地块。
  2. 检查该地块的前后是否为空 (即 flowerbed[i-1]flowerbed[i+1] 是否都为 0 或者 i 在边界)。
  3. 如果可以种花,就将 flowerbed[i] 设为 1 并减少 n 的数量。
  4. 如果 n 变成 0,提前返回 True,表示可以种下所有的花。
  5. 遍历结束后,如果仍然 n > 0,返回 False

代码实现如下:

python 复制代码
from typing import List

def canPlaceFlowers(flowerbed: List[int], n: int) -> bool:
    length = len(flowerbed)
    
    for i in range(length):
        if flowerbed[i] == 0:
            prev_empty = (i == 0 or flowerbed[i - 1] == 0)  # 边界或前一个为空
            next_empty = (i == length - 1 or flowerbed[i + 1] == 0)  # 边界或后一个为空
            
            if prev_empty and next_empty:  # 满足种植条件
                flowerbed[i] = 1
                n -= 1
                if n == 0:
                    return True  # 直接返回

    return n <= 0  # 如果 n 还大于 0,说明不能全部种下

# 测试
print(canPlaceFlowers([1, 0, 0, 0, 1], 1))  # True
print(canPlaceFlowers([1, 0, 0, 0, 1], 2))  # False
print(canPlaceFlowers([0, 0, 1, 0, 0], 1))  # True

复杂度分析:

  • 时间复杂度:O(n),只需要遍历一遍数组。
  • 空间复杂度:O(1),仅使用了常数额外空间。

这样可以高效判断能否种入 n 朵花,且尽可能早返回结果。

相关推荐
.道阻且长.9 小时前
2.LeetCode算法习题讲解--双指针--复写零
算法·leetcode·职场和发展
To_OC11 小时前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
Forever Nore14 小时前
学完C语言力扣第一题做不来正常吗
数据结构·算法
hansang_IR14 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
Tisfy16 小时前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表
lucas_AI16 小时前
Q-CueGraph:你的多模态大模型会 zoom,但真的知道该看哪儿吗?
人工智能·算法
kaixin_啊啊17 小时前
test_机器学习算法学习
学习·算法·机器学习
liulilittle17 小时前
MOE路由:路由(logits: top-k/8)
c++·人工智能·算法·机器学习·llm
旖旎夜光17 小时前
LeetCode 11:盛最多水的容器(双指针问题) —— 题解
数据结构·c++·算法·leetcode·双指针