[LeetCode] Can Place Flowers

아르당·약 20시간 전

LeetCode

목록 보기
133/134
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

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

0과 1로 이루어진 정수 배열 flowerbed가 주어졌을 때(0은 빈화단, 1은 빈 화단이 아님), 인접한 꽃이 없도록 하는 규칙을 어기지 않고 n개의 새로운 꽃을 심을 수 있다면 true, 그렇지 않다면 false를 반환해라.

Example

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

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

Constraints

  • 1 <= flowerbed.length <= 2 * 10^4
  • flowerbed[i]는 0 또는 1이다.
  • 화단에 두 꽃은 인접하지 않다.
  • 0 <= n <= flowerbed.length

Solved

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        for(int i = 0; i < flowerbed.length; i++){
            boolean left = i == 0 || flowerbed[i - 1] == 0;
            boolean right = i == flowerbed.length - 1 || flowerbed[i + 1] == 0;

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

        return n <= 0;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글