描述
假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。
示例 1:
输入: flowerbed = [1,0,0,0,1], n = 1
输出: True
示例 2:
输入: flowerbed = [1,0,0,0,1], n = 2
输出: False
注意:
数组内已种好的花不会违反种植规则。
输入的数组长度范围为 [1, 20000]。
n 是非负整数,且不会超过输入数组的大小。
思路
贪心策略,找到能种的地,如果前后都没种则该地可以种,将当前位置的数组置1,可以种的数量加1,如果n不大于可以种的数量则返回true
class Solution {
public:
bool canPlaceFlowers(vector<int>& f, int n) {
int cnt=0;
for(int i=0;i<f.size();i++){
if(!f[i]){
int prev=(i==0)?0:f[i-1];
int next=(i==f.size()-1)?0:f[i+1];
if(!prev&&!next){
cnt++;
f[i]=1;
}
}
}
return n<=cnt;
}
};
在找到满足条件的点后,下个点肯定是不能放的,所以可以将i+1直接跳到下下个点,这样就不用更改原数组。
class Solution {
public:
bool canPlaceFlowers(vector<int>& f, int n) {
int cnt=0;
for(int i=0;i<f.size();i++){
if(!f[i]){
int prev=(i==0)?0:f[i-1];
int next=(i==f.size()-1)?0:f[i+1];
if(!prev&&!next){
cnt++;
i++;
}
}
}
return n<=cnt;
}
};
解法二:
数出有多少个0,计算
出能种多少花,注意开头和结尾如果有0的话,计算的结果要加1
class Solution {
public:
bool canPlaceFlowers(vector<int>& f, int n) {
int cnt=1;
int res=0;
for(int i=0;i<f.size();i++){
if(!f[i]){
cnt++;
}
else{
res+=(cnt-1)/2;
cnt=0;
}
}
if(cnt)res+=cnt/2;
return res>=n;
}
};
参考:
https://leetcode.com/problems/can-place-flowers/discuss/103898/Java-Greedy-solution-O(flowerbed)-beats-100
https://leetcode.com/problems/can-place-flowers/discuss/103883/Java-Very-easy-solution
https://leetcode.com/problems/can-place-flowers/discuss/103933/simplest-c%2B%2B-code