[LeetCode]605. Can Place Flowers
题目描述
思路
贪心可解,遍历一次
代码
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int count = 0, len = flowerbed.size();
for (int i = 0; i < len; ++i) {
if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == len - 1 || flowerbed[i + 1] == 0)) {
flowerbed[i] = 1;
++count;
}
if (count >= n)
return true;
}
return false;
}
};
int main() {
vector<int> flowerbed = { 1, 0, 0, 0, 0, 1 };
Solution s;
cout << s.canPlaceFlowers(flowerbed, 2) << endl;
system("pause");
return 0;
}