Leetcode 605. Can Place Flowers with Python

Alpha, Orderly·2023년 3월 20일
0

leetcode

목록 보기
51/89
post-thumbnail

문제

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.

새싹이 몇개 심어진 화분이 있습니다.
꽃은 근처에 새싹이 있을시 심어질수 없습니다.

0 혹은 1로 이루어진 정수 배열이 주어집니다.
0은 화분의 비어있는 부분을 의미하고, 1은 비어있지 않음을 의미합니다.
n은 심어야하는 꽃의 갯수를 의미합니다.
이 화분에 n개의 꽃을 심을수 있을지를 boolean 값으로 리턴하세요.

예시

Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Explanation : 2번 Index 자리에 1개의 꽃을 심을수 있다.

제한

  • 1<=flowerbed.length<=21041 <= flowerbed.length <= 2 * 10^4
  • flowerbed[i]flowerbed[i] is 0 or 1.
  • 0<=n<=flowerbed.length0 <= n <= flowerbed.length

풀이법

왼쪽부터 선형검색해 꽃이 최대로 심어질수 있는 갯수를 구합니다.

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        left = 0
        for index in range(0, len(flowerbed)):
            if len(flowerbed) == 1:
                left = 1 if flowerbed[0] == 0 else 0
                break
            if flowerbed[index] == 0:
                if index == 0 and len(flowerbed) > 1:
                    if flowerbed[1] != 1:
                        flowerbed[0] = 1
                        left += 1
                elif index == len(flowerbed)-1 and len(flowerbed) > 1:
                    if flowerbed[len(flowerbed)-2] != 1:
                        flowerbed[len(flowerbed)-1] = 1
                        left += 1
                else:
                    if flowerbed[index-1] == 0 and flowerbed[index+1] == 0:
                        flowerbed[index] = 1
                        left += 1
        return left >= n
profile
만능 컴덕후 겸 번지 팬

0개의 댓글