zoukankan      html  css  js  c++  java
  • [LeetCode] Can Place Flowers

    Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.

    Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.

    Example 1:

    Input: flowerbed = [1,0,0,0,1], n = 1
    Output: True

    Example 2:

    Input: flowerbed = [1,0,0,0,1], n = 2
    Output: False

    Note:

    1. The input array won't violate no-adjacent-flowers rule.
    2. The input array size is in the range of [1, 20000].
    3. n is a non-negative integer which won't exceed the input array size.

    判断一个花床中可否放置数量为n盆花。要求花与花之间必须有一个空的间隔。

    也就是说除了边界,必须有连续3个值都为0才可以放置1盆花。如[1,0,0,0,1]

    这时需要判断边界值,因为在[0,0,1,0]或[0,1,0,0]这种情况下也可以放置1盆花。所以要在flowerbed的首位各放置一个0值来保证在这种情况下成立。

    需要注意的是对flowerbed的遍历是从1~n-1。

    class Solution {
    public:
        bool canPlaceFlowers(vector<int>& flowerbed, int n) {
            flowerbed.insert(flowerbed.begin(), 0);
            flowerbed.push_back(0);
            for (int i = 1; i < flowerbed.size() - 1; i++) {
                if (flowerbed[i - 1] + flowerbed[i] + flowerbed[i + 1] == 0) {
                    i++;
                    n--;
                }
            }
            return n <= 0;
        }
    };
    // 16 ms
  • 相关阅读:
    XSS的本质和防御
    关于网站的数据安全总结
    教培行业的复杂性
    教育到底想要什么(一)
    如何在流中重复获取body数据内容
    教育到底想要什么(二)
    鼓吹海
    翻译:三分钟学懂JSON
    翻译:ASP.NET MVC 3:Razor的隐式和显示代码嵌入
    分享到各种热门网站的html代码实现
  • 原文地址:https://www.cnblogs.com/immjc/p/7873764.html
Copyright © 2011-2022 走看看