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 n new flowers can be planted in it without violating the no-adjacent-flowers rule.
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,如果n等于,意味着不种花,则都返回true
2,如果长度小于等于2,且数组和为1,返回false
3,如果长度小于等于2,且数组和为0,返回false
4,判断当前数以及前后是否为0,若是,种一棵花,置当前数为1,N--,最后n小于等于0,则表示可以种下
#pragma once
#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
if (n == 0)//如果n等于,意味着不种花,则都返回true
{
return true;
}else if (flowerbed.size() < 1 ||( flowerbed.size() <= 2 && 1==accumulate(flowerbed.begin(), flowerbed.end(), 0)))
//如果长度小于等于2,且数组和为1,返回false
{
return false;
}
else if (flowerbed.size() <= 2 && 1 == accumulate(flowerbed.begin(), flowerbed.end(), 0))
//如果长度小于等于2,且数组和为0,返回false
{
return true;
}
//判断当前数以及前后是否为0,若是,种一棵花,置当前数为1,N--,最后n小于等于0,则表示可以种下
for (int i = 0; i < flowerbed.size(); i++)
{
if (i == 0 && flowerbed[i] == 0&& flowerbed[i+1]==0)
{
n--;
flowerbed[i] = 1;
}
else if (i > 1 && i < flowerbed.size() - 1 && flowerbed[i] ==0&& flowerbed[i - 1] ==0&& flowerbed[i + 1] == 0)
{
n--;
flowerbed[i] = 1;
}
else if (flowerbed[i]==0&&i == flowerbed.size() - 1 && flowerbed[flowerbed.size() - 2] == 0)
{
n--;
break;
}
}
if (n <= 0)
{
return true;
}
else
{
return false;
}
}
};