Problem Solving/LeetCode
2023.08.08 Today's Challenge
fabichoi
2023. 8. 8. 23:45
https://leetcode.com/problems/search-in-rotated-sorted-array/
Search in Rotated Sorted Array - LeetCode
Can you solve this real interview question? Search in Rotated Sorted Array - There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <=
leetcode.com
이분탐색으로 풀면 되는 문제.
class Solution:
def search(self, nums: List[int], target: int) -> int:
n = len(nums)
l, r = 0, n-1
while l <= r:
m = l + (r - l) // 2
if nums[m] == target:
return m
elif nums[m] >= nums[l]:
if target >= nums[l] and target < nums[m]:
r = m - 1
else:
l = m + 1
else:
if target <= nums[r] and target > nums[m]:
l = m + 1
else:
r = m - 1
return -1
반응형