1. 程式人生 > 實用技巧 >605. 種花問題

605. 種花問題

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

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

示例 1:

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

示例 2:

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

注意:

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

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/can-place-flowers


思路:

只要回答能不能種下就行,那就把能種下的情況都試一下,每次種下一朵就0變1,計數器+1

最終的計數結果和n比較一下,搞定

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
    int len = flowerbed.length;
    int cnt = 0;
    for (int i = 0; i < len && cnt < n; i++) {
        
if (flowerbed[i] == 1) { continue; } int pre = i == 0 ? 0 : flowerbed[i - 1]; int next = i == len - 1 ? 0 : flowerbed[i + 1]; if (pre == 0 && next == 0) { cnt++; flowerbed[i] = 1; } } return cnt >= n; } }

Solution Two (第一個是參考別人的,第二個是我寫的,發現了,還是有差距的)

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int count = 0;
        if (flowerbed.length == 1 && flowerbed[0] == 0){
            count++;
        }else {
            for (int i = 0; i < flowerbed.length; i++) {
                if (i ==0 && flowerbed[0] == 0 && flowerbed[1] == 0 ){
                    flowerbed[i] = 1;
                    count ++;
                }else if (i ==0 && flowerbed[0] == 0 && flowerbed[1] == 1){
                    continue;
                }
                else if(i == flowerbed.length-1 && flowerbed[flowerbed.length-1] == 0 && flowerbed[flowerbed.length-2] == 0){
                    flowerbed[flowerbed.length - 1] = 1;
                    count ++;
                }else if (i == flowerbed.length-1 && flowerbed[flowerbed.length-1] == 0 && flowerbed[flowerbed.length-2] == 1){
                    continue;
                }
                else if(flowerbed[i] == 0 && flowerbed[i-1] ==0 && flowerbed[i + 1] == 0){
                    flowerbed[i] = 1;
                    count++;
                }else {
                    continue;
                }
            }
        }
        return count >= n;
    }
}