https://leetcode.com/problems/can-place-flowers
배열 주어지면, 근접하지 않게 1 심기
public boolean canPlaceFlowers(int[] flowerbed, int n) {
if (n == 0) {
return true;
}
if (flowerbed.length == 1 && flowerbed[0] == 0) {
return n <= 1;
}
if (flowerbed.length == 2 && flowerbed[0] == 0 && flowerbed[1] == 0) {
return n <= 1;
}
for (int i = 0; i < flowerbed.length; i++) {
if (i == 0) {
if (flowerbed[i] == 0 && flowerbed[i+1] == 0) {
n--;
flowerbed[i] = 1;
}
}
else if (i == flowerbed.length - 1) {
if (flowerbed[i] == 0 && flowerbed[i-1] == 0) {
n--;
flowerbed[i] = 1;
}
}
else if (flowerbed[i-1] == 0 && flowerbed[i] == 0 && flowerbed[i+1] == 0) {
n--;
flowerbed[i] = 1;
}
if (n == 0) {
return true;
}
}
return false;
}
n=0일때, 배열 크기 1/2일 때, 하나하나 다 체크해줬음.. < 나도 잘 이해 안 간다
(K 코드) 맨 앞 뒤로 1 0 / 0 1 추가해준 다음에 1로 구분되는 0들에 최대로 몇 개 심을 수 있는지 +=
(Editorial)
안 심어져 있는 자리(0)에 양 옆이 비었는지 확인하고
첫 번째나 마지막 자리라면 오른쪽/왼쪽 자리만 확인해준다.
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = 0;
for (int i = 0; i < flowerbed.length; i++) {
if (flowerbed[i] == 0) {
// Check if the left and right plots are empty.
boolean emptyLeftPlot = (i == 0) || (flowerbed[i - 1] == 0);
boolean emptyRightPlot = (i == flowerbed.length - 1) || (flowerbed[i + 1] == 0);
// If both plots are empty, we can plant a flower here.
if (emptyLeftPlot && emptyRightPlot) {
flowerbed[i] = 1;
count++;
}
}
}
return count >= n;
}