Skip to content

Latest commit

 

History

History
46 lines (35 loc) · 1.72 KB

풀이_LC605.md

File metadata and controls

46 lines (35 loc) · 1.72 KB

🌸 LeetCode 605. Can Place Flowers

  • Date : 2021.06.20(일)
  • Time : 20분

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

Constraints

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

Example

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



풀이

    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        if len(flowerbed) < n :
            return False
    
        flowerbed.insert(0, 0)
        flowerbed.append(0)

        length = len(flowerbed)
        flower = 0
        idx = 1

        while idx < length - 1:
            if flowerbed[idx - 1:idx + 2] == [0, 0, 0]:
                flower += 1
                idx += 2
            else:
                idx += 1

        return flower >= n

: [0,0,0]을 꽃을 심을 수 있는 기준으로 잡았다. 꽃을 심으면 양 옆에 꽃 보호 할 수 있어야하는 0이 있어야하기 때문에 [0,0,0] 일 때 가운데에 꽃을 심을 수 있는 기준으로 보았다. 그래서 맨 앞과 뒤에 임시로 0을 삽입해 준 후 시작하였다. 배열을 3개씩 끊어서 [0,0,0] 인지 검사하였다. 또한 여기서 중요한 것은 꽃은 가운데 심는다는 것이다. 그렇기 때문에 꽃을 심을 수 있다면 기준점이 +2가 되야한다. +1은 화단이기 때문이다.