LeetCode日常刷題605
阿新 • • 發佈:2019-01-07
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 是非負整數,且不會超過輸入陣列的大小。
class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { int num = 0; if(flowerbed.length<=2){ for(int temp:flowerbed){ if(temp == 1&&n>0||n>1){ return false; } } return true; }else{ int fsum = 0; int snum = 0; if(flowerbed[0]==0&&flowerbed[1]==0){ num++; snum = 1; }else if(flowerbed[0]==1&&flowerbed[1]==0){ snum = 1; }else if(flowerbed[0]==0&&flowerbed[1]==1){ snum = 2; }else{ snum = 2; } for(int i=snum;i<flowerbed.length;i++){ if(flowerbed[i]==0){ fsum++; }else{ fsum = 0; } if(fsum==3){ num++; fsum=1; } } if(flowerbed.length>4){ if(flowerbed[flowerbed.length-4]!=1&&flowerbed[flowerbed.length-1]==0&&flowerbed[flowerbed.length-2]==0){ num++; } }else if(flowerbed.length==3){ if(flowerbed[flowerbed.length-1]==0&&flowerbed[flowerbed.length-2]==0){ num++; } } if(num<n){ return false; }else{ return true; } } } }