[Leetcode] 力扣605:种花问题

在这里插入图片描述
思路
贪心思想,遍历数组,能种花的地方就把花种上。注意判断条件写好。

class Solution {
    
    
public:
    bool canPlaceFlowers(vector<int>& flowerbed, int n) {
    
    
        for (int i = 0; i < flowerbed.size(); i++) {
    
    
            if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)) {
    
    
                --n;
                if (n <= 0) return true;
                flowerbed[i] = 1;
            }
        }
        return n <= 0;
    }
};


猜你喜欢

转载自blog.csdn.net/weixin_44537258/article/details/112063306
今日推荐