题目来源【Leetcode】
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不能挨着,然后问你能否放所给的花的朵数,刚开始我的代码是这样的,运行时间比较长,因为要判断是否在两端的情况,如下:
class Solution {
public:
bool canPlaceFlowers(vector<int>& nums, int n) {
int count = 0;
for(int i = 0; i < nums.size() ; i++){
if(nums[i] == 0 && i-1 >=0 && i+1 < nums.size()){
if(nums[i-1] == 0 && nums[i+1] == 0){
count++;
nums[i] = 1;
}
}
else if(nums[i] == 0 && i == 0){
if(nums[i+1] == 0){
count++;
nums[i] = 1;
}
}
else if(nums[i] == 0 && i == nums.size()-1 ){
if(nums[i-1] == 0){
count++;
nums[i] = 1;
}
}
}
if(n <= count)return true;
else return false;
}
};
后来,在头尾都插入一个0,就可以省事很多,运行时间也减少了许多,如下:
class Solution {
public:
bool canPlaceFlowers(vector<int>& nums, int n) {
nums.insert(nums.begin(),0);
nums.push_back(0);
int count = 0;
for(int i = 1; i < nums.size()-1; i++){
if(nums[i] == 0){
if(nums[i-1] == 0 && nums[i+1] == 0){
count++;
nums[i] = 1;
}
}
}
if(n <= count)return true;
else return false;
}
};