LeetCode 题解工作台

种花问题

假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 给你一个整数数组 flowerbed 表示花坛,由若干 0 和 1 组成,其中 0 表示没种植花, 1 表示种植了花。另有一个数 n ,能否在不打破种植规则的情况下种入 n 朵花…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 贪心·invariant

bolt

答案摘要

我们直接遍历数组 ,对于每个位置 ,如果 ,并且其左右相邻位置都为 ,则我们可以在该位置种花,否则不能。最后我们统计可以种下的花的数量,如果其不小于 ,则返回 ,否则返回 。 时间复杂度 ,其中 是数组 的长度。我们只需要遍历数组一次。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。

给你一个整数数组 flowerbed 表示花坛,由若干 01 组成,其中 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]01
  • flowerbed 中不存在相邻的两朵花
  • 0 <= n <= flowerbed.length
lightbulb

解题思路

方法一:贪心

我们直接遍历数组 flowerbedflowerbed,对于每个位置 ii,如果 flowerbed[i]=0flowerbed[i]=0,并且其左右相邻位置都为 00,则我们可以在该位置种花,否则不能。最后我们统计可以种下的花的数量,如果其不小于 nn,则返回 truetrue,否则返回 falsefalse

时间复杂度 O(n)O(n),其中 nn 是数组 flowerbedflowerbed 的长度。我们只需要遍历数组一次。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
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
speed

复杂度分析

指标
时间O(n)
空间O(1)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

种花问题题解:贪心·invariant | LeetCode #605 简单