[LeetCode] 605. Can Place Flowers

2025. 3. 18. 10:41·코딩테스트/Python
728x90
반응형

🔗 Problem Link

https://leetcode.com/problems/can-place-flowers/description


❔Thinking

  • 0과 1로만 이루어진 flowerbed 배열이 주어질 때 주어진 꽃을 모두 심을 수 있다면 True, 아니라면 False를 반환한다.
  • 0인 곳에 꽃을 하나 심을 수 있고, 1이 인접하지 않아야 한다. (ex - [1,1], [0,1,1] 불가능)

💻Solution

1. 초기 풀이

def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
    flowers = 0
    if flowerbed == [0] or (flowerbed == [1] and n == 0): return True
    elif flowerbed == [1]: return False

    for i in range(len(flowerbed)):
        if (i == 0 and flowerbed[i] == flowerbed[i+1] == 0):
            flowerbed[i] = 1
            flowers += 1
        elif (i == len(flowerbed)-1 and flowerbed[i] == flowerbed[i-1] == 0):
            flowerbed[i] = 1
            flowers += 1
        elif (flowerbed[i-1] == flowerbed[i] == flowerbed[i+1] == 0):
            flowerbed[i] = 1
            flowers += 1
    return True if flowers>=n else False

 

2. 개선된 풀이

def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
    flowers, size = 0, len(flowerbed)
    
    for i in range(size):
        if flowerbed[i] == 0 and (i == 0 or flowerbed[i - 1] == 0) and (i == size - 1 or flowerbed[i + 1] == 0):
            flowerbed[i] = 1
            flowers += 1
            if flowers >= n:
                return True
    
    return flowers >= n

🗝️keypoint

  1. 현재를 기준으로 이전과 이후가 0이라면, 현재를 1로 바꿀 수 있다.
  2. 이전과 이후의 값을 확인할 경우, 배열의 크기 밖으로 벗어나는 확인은 에러가 발생한다.
  3. 현재가 0인지 확인하고, 인덱스가 양 끝인지 확인하고, 앞뒤가 0인지 확인하는 세 가지를 and로 묶어 확인할 수 있다.
저작자표시 (새창열림)

'코딩테스트 > Python' 카테고리의 다른 글

[LeetCode] 238. Product of Array Except Self  (0) 2025.03.24
[LeetCode] 345. Reverse Vowels of a String  (0) 2025.03.19
[LeetCode] 1768. Merge Strings Alternately  (0) 2025.02.26
[Programmers] Level 2. 빛의 경로 사이클  (0) 2025.02.25
[Baekjoon] 1655. 가운데를 말해요  (0) 2025.02.25
'코딩테스트/Python' 카테고리의 다른 글
  • [LeetCode] 238. Product of Array Except Self
  • [LeetCode] 345. Reverse Vowels of a String
  • [LeetCode] 1768. Merge Strings Alternately
  • [Programmers] Level 2. 빛의 경로 사이클
swwho
swwho
일상을 데이터화하다
  • swwho
    하루한장
    swwho
  • 전체
    오늘
    어제
    • 분류 전체보기 (188)
      • ML_DL (39)
        • MUJAKJUNG (무작정 시리즈) (18)
        • 딥러닝 공부하기 (21)
      • 데이터사이언스 (1)
        • EDA (1)
        • 데이터과학을 위한 통계 (0)
      • 데이터엔지니어링 (2)
      • 논문리뷰 (2)
        • Computer Vision (2)
      • Python 활용하기 (12)
      • 코딩테스트 (127)
        • Python (109)
        • MySQL (14)
      • Git (3)
      • MySQL 활용하기 (0)
      • 일상 이야기 (1)
  • 블로그 메뉴

    • 홈
    • 태그
  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
swwho
[LeetCode] 605. Can Place Flowers
상단으로

티스토리툴바