IT评测·应用市场-qidao123.com

标题: python-leetcode-种花问题 [打印本页]

作者: 水军大提督    时间: 2025-3-11 10:09
标题: python-leetcode-种花问题
605. 种花问题 - 力扣(LeetCode)


使用 贪婪算法 来解决这个问题,思绪如下:
代码实现如下:
  1. from typing import List
  2. def canPlaceFlowers(flowerbed: List[int], n: int) -> bool:
  3.     length = len(flowerbed)
  4.    
  5.     for i in range(length):
  6.         if flowerbed[i] == 0:
  7.             prev_empty = (i == 0 or flowerbed[i - 1] == 0)  # 边界或前一个为空
  8.             next_empty = (i == length - 1 or flowerbed[i + 1] == 0)  # 边界或后一个为空
  9.             
  10.             if prev_empty and next_empty:  # 满足种植条件
  11.                 flowerbed[i] = 1
  12.                 n -= 1
  13.                 if n == 0:
  14.                     return True  # 直接返回
  15.     return n <= 0  # 如果 n 还大于 0,说明不能全部种下
  16. # 测试
  17. print(canPlaceFlowers([1, 0, 0, 0, 1], 1))  # True
  18. print(canPlaceFlowers([1, 0, 0, 0, 1], 2))  # False
  19. print(canPlaceFlowers([0, 0, 1, 0, 0], 1))  # True
复制代码
复杂度分析:


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

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4