[LeetCode] 605 Can Place Flowers

황은하·2021년 6월 4일
0

알고리즘

목록 보기
48/100
post-thumbnail

Description

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.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= flowerbed.length <= 2 * 10^4
  • flowerbed[i] is 0 or 1.
  • There are no two adjacent flowers in flowerbed.
  • 0 <= n <= flowerbed.length


풀이

n개의 새로운 식물을 심을 수 있는지 여부를 묻는 문제이다. 식물은 양 옆을 한 칸씩 띄우고 심어야 한다.

  • 현재 위치가 0이고,
  • i가 처음이거나 현재 이전이 0이고,
  • i가 맨 마지막이거나 현재 다음이 0인 경우

현재 위치에 식물을 심고(0->1) n을 1개 줄인다.

n이 0과 작거나 같으면 성공이고, 아니면 실패다.


코드

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int count = n;
        if (n == 0) return true;
        if (flowerbed.length == 1) {
            if (flowerbed[0] == 0 && n == 1) return true;
            else if (flowerbed[0] == 1 && n == 1) return false;
        }

        for (int i = 0; i < flowerbed.length; i++) {
            if (i == 0 && flowerbed[i] == 0 && flowerbed[i + 1] == 0) {
                flowerbed[i] = 1;
                count--;
            }
            if (i > 0 && i < flowerbed.length - 2 && flowerbed[i] == 0 && flowerbed[i + 1] == 0 && flowerbed[i + 2] == 0) {
                flowerbed[i + 1] = 1;
                count--;
                i++;
            }
            if (i == flowerbed.length - 2 && flowerbed[i] == 0 && flowerbed[i + 1] == 0) {
                flowerbed[i + 1] = 1;
                count--;
                break;
            }
            if (i == flowerbed.length - 1 && flowerbed[i] == 0 && flowerbed[i - 1] == 0) {
                flowerbed[i] = 1;
                count--;
            }
            if (count == 0) break;
        }

        if (count == 0) return true;
        else return false;
    }
}

범위를 간추린 코드

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        if (n == 0) return true;

        for (int i = 0; i < flowerbed.length; i++) {
            if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
                flowerbed[i] = 1;
                n--;
            }
        }
        if (n <= 0) return true;
        else return false;
    }
}

알고리즘 스터디를 진행하고 나서, 팀원들의 코드를 보면서 범위를 깔끔하게 지정하는 방법을 배우게 되었다. 이렇게 간추릴 수도 있구나 생각이 들었다. 많은 코드들을 보면서 더 발전시켜야겠다.

profile
차근차근 하나씩

0개의 댓글