💻알고리즘

[LeetCode] 605. Can Place Flowers

김 진 하 2025. 8. 25. 20:57

문제

일부 화단에는 꽃이 심어져 있고, 일부 화단에는 심어져 있지 않은 긴 화단이 있습니다. 하지만 인접한 화단에는 꽃을 심을 수 없습니다.

0과 1로 구성된 정수 배열 화단(0은 비어 있음을 의미하고 1은 비어 있지 않음을 의미함)과 정수 n이 주어졌을 때, 인접 꽃 없음 규칙을 위반하지 않고 화단에 새 꽃 n개를 심을 수 있으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

 

예시

Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false

 

아이디어

public boolean canPlaceFlowers(int[] flowerbed, int n) {
    if (flowerbed.length == 1) {
        if (flowerbed[0] == 1) {
            return n <= 0;
        } else {
            return n-1 <= 0;
        }
    }

    if (flowerbed[0] == 0) {
        if (flowerbed[1] == 0) {
            flowerbed[0] = 1;
            n-=1;
        }
    }
    if (flowerbed[flowerbed.length -1] == 0) {
        if (flowerbed[flowerbed.length -2] == 0) {
            flowerbed[flowerbed.length -1] = 1;
            n-=1;
        }
    }

    for (int i = 1; i < flowerbed.length; i++) {
        if (n == 0) break;

        if (flowerbed[i] == 0 && flowerbed[i - 1] == 0 && flowerbed[i + 1] == 0) {
            flowerbed[i] = 1;
            n--;
        }

    }

    return n <= 0;
}

1차 결과