LeetCode/solutions/605. Can Place Flowers.md
2019-09-13 23:08:41 +08:00

949 B
Raw Blame History

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;
    }
};