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 朵花,且尽可能早返回结果。

相关推荐
安忘4 小时前
LeetCode 热题 -189. 轮转数组
算法·leetcode·职场和发展
Y1nhl4 小时前
力扣hot100_二叉树(4)_python版本
开发语言·pytorch·python·算法·leetcode·机器学习
曼诺尔雷迪亚兹5 小时前
2025年四川烟草工业计算机岗位备考详细内容
数据结构·数据库·计算机网络·算法
GrainChenyu5 小时前
算法.习题篇
leetcode
蜡笔小新..5 小时前
某些网站访问很卡 or 力扣网站经常进不去(2025/3/10)
算法·leetcode·职场和发展
IT猿手6 小时前
2025最新群智能优化算法:基于RRT的优化器(RRT-based Optimizer,RRTO)求解23个经典函数测试集,MATLAB
开发语言·人工智能·算法·机器学习·matlab
刘大猫266 小时前
五、MyBatis的增删改查模板(参数形式包括:String、对象、集合、数组、Map)
人工智能·算法·智能合约
修己xj6 小时前
算法系列之深度/广度优先搜索解决水桶分水的最优解及全部解
算法
_GR7 小时前
2019年蓝桥杯第十届C&C++大学B组真题及代码
c语言·数据结构·c++·算法·蓝桥杯
დ旧言~7 小时前
贪心算法三
算法·leetcode·贪心算法·动态规划·推荐算法