新年第一道Leetcode题:605.种花问题(can-place-flowers)


思路:防御式编程,在收尾都加1个0,这样方便循环


bool canPlaceFlowers(vector<int> &flowerbed, int n)
{
    if (n == 0)
        return true;
    if (flowerbed.size() == 0)
        return false;
    flowerbed.push_back(0);
    flowerbed.insert(flowerbed.begin(), 0);
    int len = flowerbed.size();
    for (int i = 1; i < len - 1; i++)
    {
        if (flowerbed[i] == 1)
            continue;
        if (flowerbed[i - 1] == 0 && flowerbed[i + 1] == 0)
        {
            n--;
            if (n == 0)
                return true;
            flowerbed[i] = 1;
            continue;
        }
    }
    return false;
}

posted @ 2021-01-01 15:05  Luweir  阅读(95)  评论(0编辑  收藏  举报