leetcode (Can Place Flowers)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/84575065

Title:Can Place Flowers    605

Difficulty:Easy

原题leetcode地址:https://leetcode.com/problems/can-place-flowers/

1. 判断当前位置的前一个数和后一个数的是0还是1,注意第一个数和最后一个数

时间复杂度:O(n),一次一层for循环,最长遍历整个数组的长度。

空间复杂度:O(n),申请的最长空间长度为n。

    /**
     * 判断当前位置的前一个数和后一个数的是0还是1
     *  注意第一个数和最后一个数
     * @param flowerbed
     * @param n
     * @return
     */
    public static boolean canPlaceFlowers(int[] flowerbed, int n) {

        if (flowerbed == null || flowerbed.length <= 0 || n > flowerbed.length) {
            return false;
        }

        int count = 0;
        for (int i = 0; i < flowerbed.length; i++) {
            if (flowerbed[i] == 0) {
                int pre = i == 0 ? 0 : flowerbed[i - 1];
                int next = i == flowerbed.length - 1 ? 0 : flowerbed[i + 1];
                if (pre == 0 && next == 00) {
                    flowerbed[i] = 1;
                    count++;
                }
            }
        }

        return count >= n;

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/84575065