这道题就是苹果数一定的情况下,能不能满足一定数量孩子的胃口。(这里可以参见上一个博文)典型的贪心算法。
class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { int count=0; for(int i=0;i<flowerbed.length;i++){ if (flowerbed[i]==0&&(i==0||flowerbed[i-1]==0)&&(i==flowerbed.length-1||flowerbed[i+1]==0)){ count++; flowerbed[i]=1; } if(count>=n) return true; } return false; } }
本题虽然简单,但是还是有易错点:
1、if语句千万注意前后两个子句的顺序,防止索引越界
2、本题中count>=n 是正确的,count==n是错误的,因为无法满足用例当n=0时