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]
μ΄λΆνμ μ°Ύλ€κ° μ°μ°ν λ€μ΄μλλ° μ¨λ 벨λ‘κ·ΈμΌ ...... μ°λ¦° μ΄κ±Έ μ΄λͺ μ΄λΌ λΆλ₯΄κΈ°λ‘ νμ΄μ β¦.β¦.β¦....