您的位置:首页 > 其它

LeetCode 605 : Can Place Flowers

2017-07-07 22:43 399 查看
LeetCode 605 : Can Place Flowers

题目大意

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.


大意:给定一个数组flowerbed和一个整型值n,元素组成为0和1,其中0代表此处为空,1代表不空,现要求在数组范围内种花,要求只能种在空的地方,且两朵花之间不相邻,问该数组是否能种下n朵花,可以返回true,不可以返回false。

思路分析&相应代码

根据题目要求可知,我们只能在值为0的位置种花,且该位置左右都必须为0,。因此我们可对每个数组位置进行遍历分析,得出可种花的数量,然后与n比较,输出结果,其中确定可以种花的位置数值要变为0。因为数组头尾位置只有一个相邻位置,所以要对这两个位置进行单独分析。得到代码如下:

初级版

class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int counter=0;
int size = flowerbed.size();
if(flowerbed[0] == 0&& flowerbed[1]==0){
flowerbed[0] = 1;
counter++;
}
for(int i=1;i<flowerbed.size()-1;i++){
if(flowerbed[i] == 0 && flowerbed[i-1]==0&&flowerbed[i+1]==0)
{
counter++;
flowerbed[i] = 1;
}
if(flowerbed[size-1]==0&&flowerbed[size-2]==0){
flowerbed[size-1]=1;
counter++;
}
}
if(counter==n || counter>n){
return true;
}
return false;
}
};


但是,很容易可以看出以上代码的比较很繁琐,而且必须比较到最后一位,才能得出结果,因此需对代码进行改进。而从上面的分析可知,代码繁琐的原因是头尾元素的相邻元素相邻元素只有2个,无法与其他元素一样进行比较,所以可以对数组添加一个头尾元素,并且添加的元素值都为0,用于辅助比较。所以得到代码如下:

升级版

class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
flowerbed.insert(flowerbed.begin(),0);
flowerbed.push_back(0);
for(int i = 1; i < flowerbed.size()-1; ++i)
{
if(flowerbed[i-1]+ flowerbed[i]+ flowerbed[i+1] == 0)
{
--n;
++i;
}
if(n<=0)
return true;

}
return false;
}
};


分析总结

因为头尾元素仅仅由于缺少前一个或者后一个元素而无法与其他元素一样进行比较,所以可以给数组添加一个头尾元素进行辅助比较;因为元素的值非0即1,所以判断元素均为0的方法为三个元素相加为0。代码达到目的即可,不要拘泥于代码要表达的含义本身。敲代码之路,任重道远!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: