classSolution{publicbooleancanPlaceFlowers(int[] flowerbed,int n){int[] a =newint[flowerbed.length];int index=0;for(int i =0; i < flowerbed.length; i++){if(flowerbed[i]==1){
a[index]=i;
index++;}}int num=0;if(index>0){for(int i =0; i < index-1; i++){int temp = a[i+1]-a[i]-1;//中间几个0if(temp>1){
num+=(a[i+1]-a[i])/2-1;}}int end = flowerbed.length-a[index-1]-1;
num=num+a[0]/2+end/2;}else{int end = flowerbed.length+1;
num = end/2;}//从第一个1开始,看他和后面的一个1差几个0,然后判断if(n<=num)returntrue;elsereturnfalse;}}
别人的思路写的:
classSolution{publicbooleancanPlaceFlowers(int[] flowerbed,int n){for(int i =0; i < flowerbed.length && n>0;){if(flowerbed[i]==1){//当前为1
i=i+2;}elseif(i==flowerbed.length-1||flowerbed[i+1]==0){//0后面为0或者这个0在末尾
n--;
i+=2;}else//0后面为1
i=i+3;}if(n>0)returnfalse;elsereturntrue;}}