你有一个长长的花坛,其中有些地块种植了,有些则没有。但是,相邻的地块不能种花。
给定一个包含 0 和 1 的整数数组花坛,其中 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++) {
// Check if the current plot is empty.
if (flowerbed[i] == 0) {
// Check if the left and right plots are empty.
bool emptyLeftPlot = (i == 0) || (flowerbed[i - 1] == 0);
bool emptyRightPlot = (i == flowerbed.size() - 1) || (flowerbed[i + 1] == 0);
// If both plots are empty, we can plant a flower here.
if (emptyLeftPlot && emptyRightPlot) {
flowerbed[i] = 1;
count++;
if (count >= n) {
return true;
}
}
}
}
return count >= n;
}
};
为什么需要返回计数,即使在输出中我们只需要 true 或 false。我知道愚蠢的问题,但可以帮助菜鸟解决问题。
它不会返回
count
。声明是
return count >= n;
这会计算比较的结果
count >= n
,是真还是假。然后它返回该结果。