[LeetCode_605] Can Place Flowers(Python)

그냥·2024년 8월 30일
0

알고리즘

목록 보기
17/23

https://leetcode.com/problems/can-place-flowers/description/?envType=study-plan-v2&envId=leetcode-75

문제


코드

# 첫번째 풀이
class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        cnt = 0 
        if len(flowerbed) <3:
            if 1 in flowerbed:
                cnt = 0
            else:
                cnt = 1
        else:
            for i in range(len(flowerbed)):
                if i == 0 and flowerbed[i] == 0 and flowerbed[i+1] == 0:
                    flowerbed[i] = 1
                    cnt += 1
                elif i == len(flowerbed) -1 and flowerbed[i] == 0 and flowerbed[i-1] == 0:
                    flowerbed[i] = 1
                    cnt += 1
                elif 0 < i < len(flowerbed) - 1 and flowerbed[i] == 0 and flowerbed[i-1] == 0 and flowerbed[i+1] == 0:
                    flowerbed[i] = 1
                    cnt += 1
        return True if cnt >= n else False 
# 최종 풀이
class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        cnt = 0 
        for i in range(len(flowerbed)):
            if flowerbed[i] == 0 and flowerbed[max(0, i-1)] == 0 and flowerbed[min(len(flowerbed)-1, i+1)] == 0:
                flowerbed[i] = 1
                cnt += 1
        return True if cnt >= n else False

Idea1

  • 순차적으로 접근 -> 1을 만났을때 양옆 확인(범위 밖을 나가지 않도록 min, max로 범위 조절) -> 조건을 만족한다면 꽃 심기(+1), 카운트 += 1

0개의 댓글