You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Can Place Flowers函数需用count判断返回布尔值而非直接返回?

问题描述

给定一个长花坛,其中部分地块已种植花卉,部分未种植。但相邻地块不能种植花卉。给定由0和1组成的整数数组flowerbed(0表示空地块,1表示已种植地块)及整数n,若可在不违反相邻不种花规则的前提下种植n朵新花,返回true,否则返回false。

示例1:

Input: flowerbed = [1,0,0,0,1], n = 1
Output: true

示例2:

Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
实现代码
class Solution {
public:
    bool canPlaceFlowers(vector<int>& flowerbed, int n) {
        int count = 0;
        for (int i = 0; i < flowerbed.size(); i++) {
            // 检查当前地块是否为空
            if (flowerbed[i] == 0) {
                // 检查左右地块是否为空
                bool emptyLeftPlot = (i == 0) || (flowerbed[i - 1] == 0);
                bool emptyRightPlot = (i == flowerbed.size() - 1) || (flowerbed[i + 1] == 0);
                
                // 左右都为空则可以种花
                if (emptyLeftPlot && emptyRightPlot) {
                    flowerbed[i] = 1;
                    count++;
                    if (count >= n) {
                        return true;
                    }
                }
            }
        }
        return count >= n;
    }
};
技术疑问与解答

疑问

该函数的输出仅需布尔值true或false,为何需要维护count计数变量,并最终返回count >= n,而非采用其他判断逻辑?

解答

维护count变量主要有两个核心原因:

  • 提前终止优化:当count达到或超过n时,直接返回true就行,不用把整个数组遍历完。比如示例1里,在索引2的位置种完花后count就等于1,刚好满足n=1,直接返回结果,省了后面没必要的遍历操作。
  • 逻辑清晰且兼容:一方面,count能直观反映实际种了多少花,调试的时候更容易排查问题;另一方面,如果后续需求变了,比如要知道最多能种多少花,这个变量直接就能用。遍历结束后用count >= n判断,也能覆盖所有没提前返回的情况,逻辑完整。

当然也可以换其他写法,比如维护一个剩余需要种的数量remaining = n,每成功种一朵就减1,当remaining <= 0时返回true,遍历完返回remaining <= 0。这种写法和用count本质是一样的,只是变量含义不同,但count的写法更直观易懂。

内容的提问来源于stack exchange,提问作者Areeb Iqbal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:26:20