class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
boolean[] check=new boolean[flowerbed.length];
for (int i = 0; i < flowerbed.length; i++) {
//1이면 true로 만들거임
if(flowerbed[i]==1){
//맨끝 애들 예외처리(1개 이상일 때)
if (flowerbed.length>1) {
if (i == 0) {
check[0] = true;
check[1] = true;
} else if (i == flowerbed.length - 1) {
check[flowerbed.length - 1] = true;
check[flowerbed.length - 2] = true;
} else {
check[i - 1] = true;
check[i] = true;
check[i + 1] = true;
}
}else{
check[i]=true;
}
}
}//for
for (int i = 0; i < n; i++) {
boolean planted=false;
int idx=0;
while (idx != flowerbed.length) {
//false 면 심기
if (check[idx] == false) {
check[idx]=true;
if(idx>0) check[idx-1]=true;
if(idx<flowerbed.length-1) check[idx+1]=true;
planted=true;
break;
}
idx++;
if (idx == flowerbed.length && planted == false) {
return false;
}
}
}//for
return true;
}
}
My code. I used boolean array to check whether the flower is planted or not.
I studied with other codes after I submitted mine.
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
if (n == 0) {
return true;
}
//n>0
for (int i = 0; i < flowerbed.length; i++) {
if (flowerbed[i] == 0) {
boolean leftEmptyPot=(i==0)||(flowerbed[i-1]==0);
boolean rightEmptyPot=(i== flowerbed.length-1)||(flowerbed[i+1]==0);
if (leftEmptyPot && rightEmptyPot) {
flowerbed[i]=1;
n--;
}
if (n==0) return true;
}
}
return false;
}
}
This code checks right and left of the selected index, so the time duration is lesser than mine.
https://velog.io/@leejoycemiles/How-to-Attract-Pollinators-to-Your-Garden-with-Flowers-A-Simple-Guide