반응형
problem : https://leetcode.com/problems/search-in-rotated-sorted-array/
code :
class Solution:
def search(self, nums: List[int], target: int) -> int:
def findPivot(nums):
left = 0
right = len(nums)-1
while left<=right:
mid = right - int((right-left)/2)
print(f'mid:{mid}')
if mid ==0 or nums[mid-1] > nums[mid]:
return mid
if nums[mid] > nums[0] :
left = mid+1
else:
right = mid-1
return 0
def binarySearch(nums, left, right, target):
while left<=right:
mid = left+ int((right-left)/2)
if nums[mid]==target:
return mid
if nums[mid] < target :
left = mid+1
else :
right = mid-1
return -1
pivot = findPivot(nums)
print(f'pivot{pivot}')
if pivot == 0 or nums[0] >target :
return binarySearch(nums, pivot, len(nums)-1, target)
else :
return binarySearch(nums, 0, pivot-1, target)
반응형