Leetcode 605.種花問題
阿新 • • 發佈:2019-02-15
false lower lean cef ++ 範圍 規則 flow turn
種花問題
假設你有一個很長的花壇,一部分地塊種植了花,另一部分卻沒有。可是,花卉不能種植在相鄰的地塊上,它們會爭奪水源,兩者都會死去。
給定一個花壇(表示為一個數組包含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 是非負整數,且不會超過輸入數組的大小。
思路
1 public class Solution { 2 public boolean canPlaceFlowers(int[] flowerbed, int n) { 3 int i = 0, count = 0; 4 while (i < flowerbed.length) { 5 if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {6 flowerbed[i] = 1; 7 count++; 8 } 9 i++; 10 } 11 return count >= n; 12 } 13 }
Leetcode 605.種花問題