leetcode_数组_605_种花问题

class Solution {
public:
bool canPlaceFlowers(vector& flowerbed, int n) {
int pre=-2,cur=-2,cnt=0;
for(int i=0;i {
if(flowerbed[i]==0)
continue;
else
{
if(flowerbed[i]==1)
{
cur=i;
cnt+=max((cur-pre-2)/2,0);
pre=i;
}
}
}
cnt+=(flowerbed.size()-pre-1)/2;
return cnt>=n;
}
};

//优秀
class Solution {
public:
bool canPlaceFlowers(vector& flowerbed, int n) {
int len = flowerbed.size();
if (len < n)
{
return false;
}

//给原数组前后各加一个0,遍历数组,找到连续的三个零
vector tmp(flowerbed);
tmp.insert(tmp.begin(), 0);
tmp.push_back(0);
int lenTmp = tmp.size();
for (int i = 1; i < lenTmp - 1; ++i)
{
if ((tmp.at(i - 1) == 0)
&& (tmp.at(i) == 0)
&& (tmp.at(i + 1) == 0))
{
–n;
++i;
}
}
return n <= 0;
};

你可能感兴趣的:(leetcode,数据结构与算法)