Create 605. Can Place Flowers.md

This commit is contained in:
唐树森 2018-09-11 19:57:28 +08:00 committed by GitHub
parent a47274f75d
commit 8f05227c3b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

23
605. Can Place Flowers.md Normal file
View File

@ -0,0 +1,23 @@
# [605. Can Place Flowers](https://leetcode.com/problems/can-place-flowers/description/)
# 思路
题意就是将数组中的某些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;
}
};
```