算法挑战100天 - Eight(easy)

2020-09-23  本文已影响0人  holmes000

类别:数组

题目: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. 常数优化,在循环时,满足条件就返回;
上一篇下一篇

猜你喜欢

热点阅读