[LeetCode]605. Can Place Flowers

[LeetCode]605. Can Place Flowers

题目描述

[LeetCode]605. Can Place Flowers_第1张图片

思路

贪心可解,遍历一次

代码

#include 
#include 

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

你可能感兴趣的:(leetcode)