[LeetCode / Easy] 605. Can Place Flowers (Java)

이하얀·2025년 2월 2일
0

📙 LeetCode

목록 보기
6/13

💬 Info



Problem

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 true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.



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 * 10410^4
  • flowerbed[i] is 0 or 1
  • There are no two adjacent flowers in flowerbed.
  • 0 <= n <= flowerbed.length


문제 이해

  • 꽃을 심는 위치를 탐색하는 문제(n을 감소시켜 0이 될 경우 True를 반환)


알고리즘

풀이 시간 : 15분

  • 위치 확인 & 꽃 심기 체크
    • flowerbed[i](현재 위치)가 0, i-1과 i+1(양 옆)가 비어 있다면 꽃 심기
  • 꽃 심을 때 n 감소: n이 0이 되면 바로 True 반환
  • 탐색 끝나고 n == 0이면 True 반환
class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        for (int i = 0; i < flowerbed.length && n > 0; i++) {
            if (flowerbed[i] == 0 
                && (i == 0 || flowerbed[i - 1] == 0) 
                && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
                flowerbed[i] = 1;
                n--;
            }
        }
        return n == 0;
    }
}


결과

profile
언젠가 내 코드로 세상에 기여할 수 있도록, Data Science&BE 개발 기록 노트☘️

0개의 댓글