一、題目描述
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.
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.
二、題解
方法一:錯誤枚舉
遇到 1 就枚舉前兩個位置是否爲 0,但是沒有當前位置是 0,後序位置沒有 1 的情況。 即這種情況:
[0,0,1,0,1]
1
public boolean canPlaceFlowers(int[] f, int n) {
int count = 0, N = f.length;
for (int i = 0; i < N; i++) {
if (f[i] == 1)
continue;
for (int j = i + 2; j < N; j += 2) {
if (f[j] == 0 && f[j - 1] == 0 && f[j + 1] == 0) {
count++;
f[j] = 1;
break;
}
}
}
return count >= n;
}
防禦式編程: 一種比較直觀的做法就是在數組 f
的首尾各加 1 個前導 0,這樣就不必考慮邊界。
複雜度分析
- 時間複雜度:,
- 空間複雜度:,
方法二:貪心
- 遇到 0 就判斷它的前後是否爲 0。
- 如果
f[i-1]
與f[i+1]
都爲 0 則可種。 - 否則,跳過。
- 如果
- 邊界問題:
- 若
i = 0
,則默認last
爲 0. - 若
i = N-1
,則默認next
= 0
- 若
public boolean canPlaceFlowers(int[] f, int n) {
int count = 0, N = f.length;
for (int i = 0; i < N; i++) {
if (f[i] == 1)
continue;
int last = i == 0 ? 0 : f[i-1];
int next = i == N-1 ? 0 : f[i+1];
if (last == 0 && next == 0) {
count++;
f[i] = 1;
}
}
return count >= n;
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,