[파이썬] LeetCode 34. Find First and Last Position of Element in Sorted Array πŸ‘‰πŸ» 이뢄 탐색

Youngeui HongΒ·2023λ…„ 10μ›” 28일
0

μ•Œκ³ λ¦¬μ¦˜

λͺ©λ‘ 보기
5/12

πŸ”— 문제

34. Find First and Last Position of Element in Sorted Array

πŸ‘€ 이뢄탐색

이뢄탐색과 κ΄€λ ¨ν•˜μ—¬ μžμ„Έν•œ λ‚΄μš©μ€ μ•„λž˜ ν¬μŠ€νŒ…μ— μ •λ¦¬λ˜μ–΄ μžˆλ‹€.

πŸ‘‰πŸ» 이뢄탐색 더 μ•Œμ•„λ³΄κΈ°

πŸ‘©πŸ»β€πŸ’» λ‹΅μ•ˆ

🚨 이뢄탐색 λ¬Έμ œμ—μ„œ μ£Όμ˜ν•  점

  • while left + 1 < rightλ₯Ό μ‚¬μš©ν•˜λ©΄ mid + 1 / mid - 1 이런 μ‹μœΌλ‘œ ν•  ν•„μš”κ°€ μ—†λ‹€.
  • left, right의 μ΄ˆκΈ°κ°’μ„ 닡이 될 수 μžˆλŠ” κ°’μœΌλ‘œ μ„€μ •ν•˜μ§€ 말 것 (그보닀 ν•˜λ‚˜ 적고, ν•˜λ‚˜ 큰 κ°’μœΌλ‘œ μ„€μ •ν•  것)
class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if not nums or target not in nums:
            return [-1, -1]

        # κ°€μž₯ 첫 번째둜 target이 λ˜λŠ” 인덱슀 μ°ΎκΈ°
        def find_first_occurrence(nums, target):
            left, right = -1, len(nums)
            while left + 1 < right:
                mid = (left + right) // 2
                if nums[mid] < target:
                    left = mid
                else:
                    right = mid

            return right

        # κ°€μž₯ λ§ˆμ§€λ§‰μœΌλ‘œ target이 λ˜λŠ” 인덱슀 μ°ΎκΈ°
        def find_last_occurrence(nums, target):
            left, right = -1, len(nums)
            while left + 1 < right:
                mid = (left + right) // 2
                if nums[mid] <= target:
                    left = mid
                else:
                    right = mid

            return left

        first_occurrence = find_first_occurrence(nums, target)
        last_occurrence = find_last_occurrence(nums, target)

        return [first_occurrence, last_occurrence]
profile
Frontend Web Developer

1개의 λŒ“κΈ€

comment-user-thumbnail
2023λ…„ 10μ›” 28일

이뢄탐색 μ°Ύλ‹€κ°€ μš°μ—°νžˆ λ“€μ–΄μ™”λŠ”λ° μ˜¨λ‹ˆ λ²¨λ‘œκ·Έμ•Ό ...... 우린 이걸 운λͺ…이라 λΆ€λ₯΄κΈ°λ‘œ ν–ˆμ–΄μš” ✦.✦.✦....

λ‹΅κΈ€ 달기