Search

Can Place Flowers

문제 설명 : 화단의 상태를 나타내는 배열을 제공한다. 이때 심어야 할 꽃을 모두 심을 수 있는 여부를 반환
풀이 방법
구현 문제이다. 조건에 맞게 구현하면 된다.
시간복잡도 : O(N)O(N)
성공 코드
class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: # 화단이 없는 경우 if len(flowerbed) == 0: return False # 꽃을 심을 수 있는지 여부 def is_able_plant(cursor): # 현 위치에 안심어져 있는 경우 if flowerbed[cursor] == 0: # 화단의 첫 위치일 때, 화단이 길이가 1보다 길면 다음 위치에 안심어져 있는지 여부를 반환 if cursor == 0: return len(flowerbed) == 1 or (len(flowerbed) > 1 and flowerbed[cursor + 1] == 0) # 화단의 마지막 위치 & 이전 화단에 안심어져 있는경우 if cursor == len(flowerbed) - 1: return flowerbed[cursor - 1] == 0 # 현 위치의 양쪽 위치(이전/이후)에 안 심어져 있는지 여부를 반환 return flowerbed[cursor - 1] == 0 and flowerbed[cursor + 1] == 0 return False for cursor in range(len(flowerbed)): # 꽃을 심을 수 있는 위치로 이동 if cursor + 1 < len(flowerbed) and flowerbed[cursor] == 1: continue # 이후 위치들 확인 if n > 0 and is_able_plant(cursor): flowerbed[cursor] = 1 n -= 1 return n == 0
Python
복사