1. 程式人生 > >C#LeetCode刷題之#605-種花問題( Can Place Flowers)

C#LeetCode刷題之#605-種花問題( Can Place Flowers)

問題

假設你有一個很長的花壇,一部分地塊種植了花,另一部分卻沒有。可是,花卉不能種植在相鄰的地塊上,它們會爭奪水源,兩者都會死去。

給定一個花壇(表示為一個數組包含0和1,其中0表示沒種植花,1表示種植了花),和一個數 n 。能否在不打破種植規則的情況下種入 n 朵花?能則返回True,不能則返回False。

輸入: flowerbed = [1,0,0,0,1], n = 1

輸出: True

輸入: flowerbed = [1,0,0,0,1], n = 2

輸出: False

注意:

陣列內已種好的花不會違反種植規則。
輸入的陣列長度範圍為 [1, 20000]。
n 是非負整數,且不會超過輸入陣列的大小。

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.

Input: flowerbed = [1,0,0,0,1], n = 1

Output: True

Input: flowerbed = [1,0,0,0,1], n = 2

Output: False

Note:

The input array won't violate no-adjacent-flowers rule.
The input array size is in the range of [1, 20000].
n is a non-negative integer which won't exceed the input array size.

示例

public class Program {

    public static void Main(string[] args) {
        int[] nums = null;

        nums = new int[] { 1, 0, 0, 0, 1 };
        var res = CanPlaceFlowers(nums, 1);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static bool CanPlaceFlowers(int[] flowerbed, int n) {
        //該題比較簡單,處理好邊界即可
        //需要種植的花為0,總是可以
        if(n == 0) return true;
        //陣列為0,不可種植
        if(flowerbed.Length == 0) {
            return false;
        }
        //當陣列為1時,根據是否種植直接判定即可
        if(flowerbed.Length == 1) {
            if(flowerbed[0] == 0) {
                return true;
            } else {
                return false;
            }
        }
        //記錄可以種植的數量
        int count = 0;
        //前2個分析
        if(flowerbed.Length >= 2 &&
           flowerbed[0] == 0 &&
           flowerbed[1] == 0) {
            flowerbed[0] = 1;
            count++;
        }
        //連續3個為0時,可種植
        for(int i = 1; i < flowerbed.Length - 1; i++) {
            if(flowerbed[i - 1] == 0 &&
               flowerbed[i] == 0 &&
               flowerbed[i + 1] == 0) {
                count++;
                flowerbed[i] = 1;
            }
        }
        //後2個分析
        if(flowerbed.Length >= 2 &&
           flowerbed[flowerbed.Length - 1] == 0 &&
           flowerbed[flowerbed.Length - 2] == 0) {
            flowerbed[flowerbed.Length - 1] = 1;
            count++;
        }
        //可種植數大於等於即將種植的數量時,返回true
        if(count >= n) return true;
        //無解時,返回false
        return false;
    }

}

以上給出1種演算法實現,以下是這個案例的輸出結果:

True

分析:

該題比較簡單,若使用其它ADT,可以考慮左右邊界補0的方法,這樣可以少處理部分邊界問題。

顯而易見,以上演算法的時間複雜度為: O(n) 。