class Solution:
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
# right order from mid to right
if nums[mid] < nums[right]:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
# right order from left to mid
else:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
return -1
mid = left + (right - left) // 2
mid = (left + right) // 2 과 동일하되, 오버플로우 문제 회피 위함. 파이썬의 경우 비교적 자유로움.
'CS > 알고리즘' 카테고리의 다른 글
[Leetcode] 153. Find Minimum in Rotated Sorted Array (0) | 2023.05.02 |
---|---|
[Leetcode] 74. Search a 2D Matrix (0) | 2023.05.01 |
[Leetcode] 34. Find First and Last Position of Element in Sorted Array (0) | 2023.05.01 |
[Leetcode] 17. Letter Combinations of a Phone Number (0) | 2023.05.01 |
[Leetcode] 16. 3Sum Closest (0) | 2023.05.01 |