1. 程式人生 > >LeetCode 605. Can Place Flowers

LeetCode 605. Can Place Flowers

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.

題目大意:

題目意思是要種花,種花都要求就是每盆花不能相鄰,即要間隔開。
給定過一個數組,其中的元素包括0和1,0表示空地,1表示已經種了都花。問,最多還能種多少花?
模擬種花過程,遍歷陣列,符合要求的位置進行“種花”操作,並且記錄種花盆數即可。

題目程式碼:

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)){
                flowerbed[i] = 1;
                n--;
            }    
        }
        return n <= 0;
    }
};