LeetCode 题解工作台
种花问题
假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 给你一个整数数组 flowerbed 表示花坛,由若干 0 和 1 组成,其中 0 表示没种植花, 1 表示种植了花。另有一个数 n ,能否在不打破种植规则的情况下种入 n 朵花…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 贪心·invariant
答案摘要
我们直接遍历数组 ,对于每个位置 ,如果 ,并且其左右相邻位置都为 ,则我们可以在该位置种花,否则不能。最后我们统计可以种下的花的数量,如果其不小于 ,则返回 ,否则返回 。 时间复杂度 ,其中 是数组 的长度。我们只需要遍历数组一次。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给你一个整数数组 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 * 104flowerbed[i]为0或1flowerbed中不存在相邻的两朵花0 <= n <= flowerbed.length
解题思路
方法一:贪心
我们直接遍历数组 ,对于每个位置 ,如果 ,并且其左右相邻位置都为 ,则我们可以在该位置种花,否则不能。最后我们统计可以种下的花的数量,如果其不小于 ,则返回 ,否则返回 。
时间复杂度 ,其中 是数组 的长度。我们只需要遍历数组一次。空间复杂度 。
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
flowerbed = [0] + flowerbed + [0]
for i in range(1, len(flowerbed) - 1):
if sum(flowerbed[i - 1 : i + 2]) == 0:
flowerbed[i] = 1
n -= 1
return n <= 0
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates understanding of greedy algorithms.
- question_mark
Candidate is able to explain the importance of early termination and boundary conditions.
- question_mark
Candidate can handle edge cases involving small or large flowerbed arrays.
常见陷阱
外企场景- error
Failing to account for boundary conditions (first and last plot).
- error
Incorrectly attempting to plant flowers in adjacent plots, violating the rule.
- error
Not terminating early when enough flowers are planted.
进阶变体
外企场景- arrow_right_alt
What if we need to plant more than one flower in a single pass?
- arrow_right_alt
What if the flowerbed array is larger or smaller than typical inputs?
- arrow_right_alt
How would the approach change if the flowerbed could have more complex rules, such as spacing requirements between flowers?