[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

 

posted @ 2017-11-21 16:20  immjc  阅读(196)  评论(0编辑  收藏  举报