leetcode 605. Can Place Flowers

题目:
 假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
  给定一个花坛(表示为一个数组包含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:
首先判断花盆数量是否为 1,如果是则判断有没有种花,在根据实际返回ture。定义一个累加器cnt,用于与n作比较。要判断第一盆花和最后一盆花是否满足条件,再从第三盆花开始判断,直到数到倒数第二个花盆。

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

解题思路 2:
花盆的前后插入一个空花盆,就不用再去判断第一个和最后一个了。

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