605. Can Place Flowers零一间隔种花

[抄题]:

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 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

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

  1. for循环一般还是从0到n, 如果怀疑,先做个标记,后续再改

[思维问题]:

for循环之内应该满足一个第一步的初始条件,再进行后续操作

[一句话思路]:

正常操作,直面灵魂拷问

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 最多能种的花要比实际给的花的额度更大,count >= n

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

正常操作,直面灵魂拷问

return count >= n;

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        //cc
        if (flowerbed == null || flowerbed.length == 0) {
            return false;
        }
        
        //ini
        int count = 0;
        
        //for loop as normal
        for (int i = 0; i < flowerbed.length && count <= n; i++) {
            if (flowerbed[i] == 0) {
                int prev = (i == 0) ? 0 : flowerbed[i - 1];
                int next = (i == flowerbed.length - 1) ? 0 : flowerbed[i + 1];
                
                if (prev == 0 && next == 0) {
                    count++;
                    flowerbed[i] = 1;
                }
            }
        }
        
        return count >= n;
    }
}
View Code

 

posted @ 2018-04-22 15:50  苗妙苗  阅读(132)  评论(0编辑  收藏  举报