Algorithm - Can Place Flowers(Greedy)

다용도리모콘·2021년 8월 28일
0

CodingTest

목록 보기
32/34

문제

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.

코드

function canPlaceFlowers(flowerbed: number[], n: number): boolean {
    if (n == 0) return true;

    for (var i = 0; i < flowerbed.length; i++) {
        
        if (flowerbed[i] == 1) continue;


        if ((flowerbed[i - 1] == 0 || flowerbed[i - 1] == undefined) &&
        (flowerbed[i + 1] == 0 || flowerbed[i + 1] == undefined)) {
            flowerbed[i] = 1;
            n = n - 1;
        }
        if (n == 0) return true;
    }
    return false;
};

풀이

flowerbed를 순차적으로 탐색하면서 앞, 본인, 뒤가 모두 비어 있으면 꽃을 심고 꽃 수를 차감한다. 심어야 하는 꽃의 수가 0이 되면 true를 리턴, 탐색이 끝날 때까지 리턴이 되지 않았다면 false를 리턴.

회고

typescript라서 조금 더 편하게 푼 것 같다. 처음이나 마지막에서 앞, 뒤의 화분을 보려고 할 때 kotlin이었으면 OutOfIndex를 신경써야 했을텐데 javascript는 알아서 undefined로 판단해주니까 간단했다.

0개의 댓글