605. Can Place Flowers

Numeric_combo·2024년 10월 27일

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
Example 2:

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

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        f = [0] + flowerbed + [0] # explicitly assume that there are 0s left/right-outside of flowerbed list

        for i in range(1, len(f) - 1): # skip first and last
            if f[i - 1] == 0 and f[i] == 0 and f[i + 1] == 0: # check left, target, and right
                f[i] = 1 # plat a flower
                n -= 1 # decrement the number of flowers remaining to be planted (remaining 되는 방식으로 된다는 거 잊지 말기)
        return n <= 0
        # After iterating through all plots, check if the number of flowers remaining to be planted (n) is less than or equal to 0. If so, return True, indicating that all flowers have been successfully planted without violating the adjacency rule. Otherwise, return False.

뭔가 포인터를 쓰는 것 같았는데 정확히 로직을 어떻게 짜야할지 몰라 결국 못 풀고 답안지를 봤다. easy래매...여튼 재밌던 점은 첫번째로 먼저 flowerbed 리스트에다가 양 옆으로 0이라고 함으로써 명시적으로 가정을 시키는 거였고 (첫번째 라인), 포인터를 사용하는 방식 (왼쪽, 심으려는 꽃 위치, 오른쪽)을 쓰는 법이었고 (if-clause)이었고, 제일 중요한 부분이었던 꽃을 한 번에 다 심는 게 아니라 for-loop 안에서 꽃 하나를 심는데 성공하면 꽃을 심으려는 n개를 한 개씩 줄이는 부분이었다 (n -= 1 부분).

그리고 리턴을 저런 식으로 선언함으로써 True or False를 얻어내는 방식이 있다는 걸 다시 상기시켰다.

profile
덕질기록용

0개의 댓글