605 Can Place Flowers 種花問題
Description:
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:
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:
The input array won't violate no-adjacent-flowers rule.
The input array size is in the range of [1, 20000].
n is a non-negative integer which won't exceed the input array size.
題目描述:
假設(shè)你有一個(gè)很長的花壇,一部分地塊種植了花,另一部分卻沒有??墒?,花卉不能種植在相鄰的地塊上,它們會(huì)爭奪水源,兩者都會(huì)死去。
給定一個(gè)花壇(表示為一個(gè)數(shù)組包含0和1,其中0表示沒種植花,1表示種植了花),和一個(gè)數(shù) n 。能否在不打破種植規(guī)則的情況下種入 n 朵花?能則返回True,不能則返回False。
示例 :
示例 1:
輸入: flowerbed = [1,0,0,0,1], n = 1
輸出: True
示例 2:
輸入: flowerbed = [1,0,0,0,1], n = 2
輸出: False
注意:
數(shù)組內(nèi)已種好的花不會(huì)違反種植規(guī)則。
輸入的數(shù)組長度范圍為 [1, 20000]。
n 是非負(fù)整數(shù),且不會(huì)超過輸入數(shù)組的大小。
思路:
- 遍歷花壇, 按照規(guī)則種樹即可
- 可以在花壇兩端增加兩個(gè)空的花盆, 減少判斷量
時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(1)
代碼:
C++:
class Solution
{
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n)
{
for (int i = 0; i < flowerbed.size(); i++)
{
if (!flowerbed[i] && (i == 0 or !flowerbed[i - 1]) and (i == flowerbed.size() - 1 or !flowerbed[i + 1]))
{
n--;
flowerbed[i] = 1;
}
}
return n <= 0;
}
};
Java:
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
for (int i = 0; i < flowerbed.length; i++) {
if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
n--;
flowerbed[i] = 1;
}
}
return n <= 0;
}
}
Python:
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
flowerbed = [0] + flowerbed + [0]
for i in range(1, len(flowerbed) - 1):
if not flowerbed[i] and not flowerbed[i + 1] and not flowerbed[i - 1]:
flowerbed[i] = 1
n -= 1
return n <= 0