1. 程式人生 > >leetcode (Can Place Flowers)

leetcode (Can Place Flowers)

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;

    }