링크
배열에서 해당 원소의 첫번째 위치와 마지막 위치를 구하는 문제
def searchRange(self, nums: List[int], target: int) -> List[int]:
ans = []
idx = bisect.bisect_left(nums, target)
if idx < len(nums) and target == nums[idx]:
ans.append(idx)
else:
return [-1, -1]
idx = bisect.bisect_right(nums, target)
if idx > 0 and nums[idx - 1] == target:
ans.append(idx - 1)
return ans
def searchRange(self, nums: List[int], target: int) -> List[int]:
ans = [-1, -1]
l, r = 0, len(nums) - 1
# left
while l <= r:
mid = ( l + r ) // 2
if nums[mid] == target:
if mid == 0 or mid > 0 and nums[mid - 1] != target:
ans[0] = mid
break
if nums[mid] >= target:
r = mid - 1
else:
l = mid + 1
l, r = 0, len(nums) - 1
while l <= r:
mid = ( l + r ) // 2
if nums[mid] == target:
if mid == len(nums) - 1 or mid < len(nums) - 1 and nums[mid + 1] != target:
ans[1] = mid
break
if nums[mid] > target:
r = mid - 1
else:
l = mid + 1
return ans