1. 程式人生 > >[leetcode]: 605. Can Place Flowers

[leetcode]: 605. Can Place Flowers

1.題目

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.
用一維陣列表示要種花的花床,0表示未種,1表示已種。相鄰兩處不能同時種花。給出花床的陣列和需要種花的數量n,判斷是否能把n個花種下去。

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

2.分析

相鄰位置不能同時種花,那麼可以種花分三種情況:
1) 陣列首部 00x 頭部的0可以種花
2) 陣列中間 000 中間的0可以種花
3) 陣列尾部 x00 尾部的0可以種花
遍歷一遍陣列即可。

3.程式碼

class Solution {
public:
    bool canPlaceFlowers(vector
<int>
& flowerbed, int n) { int length = flowerbed.size(); int i = 0; for (; i < length&&n > 0; i++) { if (flowerbed[i] == 0) { int left = i - 1 > 0 ? i - 1 : 0; int right = i + 1 < length - 1 ? i + 1 : length - 1
; if (flowerbed[left] == 0 && flowerbed[right] == 0) {//左右兩邊都沒有種花 flowerbed[i] = 1; --n; } } } return n == 0; } };