Question:
Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.
Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if nnew flowers can be planted in it without violating the no-adjacent-flowers rule.
假设你有一个长的花坛,其中一些地块种植,有些不是。 然而,花朵不能种植在相邻的地块上 - 他们会争取水,两者都会死亡。给定一个花坛(表示为包含0和1的数组,其中0表示空,1表示不为空),数字n,如果可以种植n个新鲜花,则不返回无相邻花规则。
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1 Output: True
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2 Output: False
Note:
- The input array won't violate no-adjacent-flowers rule.
- The input array size is in the range of [1, 20000].
- n is a non-negative integer which won't exceed the input array size.
注意:输入数组不会违反无相邻花规则。
输入数组大小在[1,20000]的范围内。
n是不会超过输入数组大小的非负整数。
思路:首先判断对于给定的数组,能够放多少数字1进去。有两个相邻的数字1就返回false.对于是数字0的元素,要检查左右两边的数字是不是0,如果是0,就可以放1,对于第一个数字,只用判断右边的数字是不是0,对于最后一个数字,只用判断左边的数字是不是0.最后求得一共能放进去1的数字的个数q与输入的n对比,如果q大于等于n,那么就返回true,否则false。
Answer:
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int i;
int q=0;
if(flowerbed[0]==0&&flowerbed[1]==0)
q=q+1;
if(flowerbed[flowerbed.size()-1]==0&&flowerbed[flowerbed.size()-2]==0)
q=q+1;
for(i==1;i<flowerbed.size()-2;i++)
{
if(flowerbed[i]==0)
{
if(flowerbed[i-1]==0&&flowerbed[i+1]==0)
{
q=q+1;
flowerbed[i]==1;
}
}
}
if(q>=n)
return true;
else
return false;
}
};Run code result:
Your input
[1,0,0,0,1] 2
Your answer
false
Expected answer
false
解决一个经典的编程问题,即在遵循特定规则的情况下确定是否可以在给定的花坛中种植指定数量的新鲜花。此问题需要考虑边界条件并进行逻辑判断。
248

被折叠的 条评论
为什么被折叠?



