greedy O(n) time O(1) space
纯粹考心细
从前往后扫,只要找到合适的位置就放,不需要考虑是否最佳,greedy是对的
- 如果f[i] == 1跳过
 
- 如果f[i] == 0 && f[i - 1] == 1跳过
 
- 如果f[i] == 0 && f[i + 1] == 1跳过
 
- –n同时一定要将f[i]改成1!!!!!!
 
- 最后一定要判断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;          }         return false;     } };
  |