美文网首页
算法挑战100天 - Eight(easy)

算法挑战100天 - Eight(easy)

作者: holmes000 | 来源:发表于2020-09-23 10:04 被阅读0次

类别:数组

题目:https://leetcode-cn.com/problems/can-place-flowers/

我的解:时间 O(n) 空间O(1)

 public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int count = 0;
        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)) {
                flowerbed[i] = 1;
                count++;
            }
        }
        if (count >= n) {
            return true;
        }
        return false;
    }

最优解:时间 O(n) 空间O(1)

public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int i = 0, count = 0;
        while (i < flowerbed.length) {
            if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
                flowerbed[i++] = 1;
                count++;
            }
             if(count>=n)
                return true;
            i++;
        }
        return false;
    }

差异点:

  1. 常数优化,在循环时,满足条件就返回;

相关文章

网友评论

      本文标题:算法挑战100天 - Eight(easy)

      本文链接:https://www.haomeiwen.com/subject/mepnyktx.html