解答
Leetcode上第605道题,我的解答:线下编译没错误,但是线上编译出错
#include <iostream>#include<vector>using std::vector;using std::cout;using std::endl;class Solution{public:int num_flag = 0;bool canPlaceFlowers(vector<int>& flowerbed, int n){for (auto it = flowerbed.begin(); it != flowerbed.end(); ++it){if (it == flowerbed.begin() || it == flowerbed.end()){if (it == flowerbed.begin()){if (*it==0 && *(it + 1) == 0){*it = 1;num_flag = num_flag + 1;}}else{if (*it==0 && *(it - 1) == 0){*it = 1;num_flag = num_flag + 1;}}}else{if (*(it - 1) == 0 && *it == 0 && *(it + 1) == 0){*it = 1;num_flag = num_flag + 1;}}}if (num_flag >= n) {return true;}else {return false;}};};void main(){vector<int> flbed = { 1,0,0,0,1,0,0};int n = 2;Solution solu;bool result = solu.canPlaceFlowers(flbed, n);if (result){cout << "可以" << endl;}else{cout << "不可以" << endl;}}
跳格子法
解题者提供的跳格子法,非常容易理解
题目要求是否能在不打破规则的情况下插入n朵花,与直接计算不同,采用“跳格子”的解法只需遍历不到一遍数组,处理以下两种不同的情况即可:
【1】当遍历到index遇到1时,说明这个位置有花,那必然从index+2的位置才有可能种花,因此当碰到1时直接跳过下一格。
【2】当遍历到index遇到0时,由于每次碰到1都是跳两格,因此前一格必定是0,此时只需要判断下一格是不是1即可得出index这一格能不能种花,如果能种则令n减一,然后这个位置就按照遇到1时处理,即跳两格;如果index的后一格是1,说明这个位置不能种花且之后两格也不可能种花(参照【1】),直接跳过3格。
当n减为0时,说明可以种入n朵花,则可以直接退出遍历返回true;如果遍历结束n没有减到0,说明最多种入的花的数量小于n,则返回false。
