mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
946 B
946 B
605. Can Place Flowers
思路
题意就是将数组中的某些0变为1且满足每个1没有相邻的1,问是否能改变n个之前为0的元素为1. 题目保证原数组每个1都没有相邻的1.
使用贪心策略即可,从前往后遍历数组,遇到能变为1的0就将其变为1,同时用count计数,当count达到n即可返回true。
注意数组首尾的特殊情况。
C++
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
if(n == 0) return true;
int count = 0;
for(int i = 0; i < flowerbed.size(); i++){
if(flowerbed[i]) continue;
if((i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)){
flowerbed[i] = 1;
if(++count == n) return true;
}
}
return false;
}
};