0%

605. Can Place Flowers

greedy O(n) time O(1) space
纯粹考心细
从前往后扫,只要找到合适的位置就放,不需要考虑是否最佳,greedy是对的

  1. 如果f[i] == 1跳过
  2. 如果f[i] == 0 && f[i - 1] == 1跳过
  3. 如果f[i] == 0 && f[i + 1] == 1跳过
  4. –n同时一定要将f[i]改成1!!!!!!
  5. 最后一定要判断n等于0!!!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int sz = flowerbed.size();
for (int i = 0; i < sz; ++i) {
if (flowerbed[i] == 0) {
if (n == 0) return true;
if (i > 0 && flowerbed[i - 1]) continue;
if (i + 1 < sz && flowerbed[i + 1]) continue;
--n;
flowerbed[i] = 1; // 放
}
}
return n == 0;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int sz = flowerbed.size();
for (int i = 0; i < sz; ++i) {
if (flowerbed[i] == 0) {
if (i > 0 && flowerbed[i - 1]) continue;
if (i + 1 < sz && flowerbed[i + 1]) continue;
--n;
flowerbed[i] = 1; // 放
}
if (n <= 0) return true; // 这里必须是小于等于0因为可能n会多减
}
return false;
}
};