leetcode 每日一题 33. 搜索旋转排序数组
二分法:
思路:
取要选择区间的中间位置,则在中间位置左边或者右边必然有一个有序数组,我们可以在通过判断target是否在有序数组来查找target位置并更新mid的值。
例如:
nums = [4,5,6,7,0,1,2] target = 0
l = 0 , r = 6 , mid = 3 , 因为nums[mid] > nums[l],又target<nums[r],则l = mid +1 = 4
l = 4 , r = 6 , mid = 5 , 因为 nums[mid] > nums[l],又target>=nums[r],则r = mid-1 = 4
l = 4 , r = 4, mid = 4,nums[mid] == target,得到结果mid = 4
代码:
class Solution: def search(self, nums: List[int], target: int) -> int: if not nums: return -1 l,r = 0,len(nums)-1 while l<=r: mid = (l+r)//2 if nums[mid] == target: return mid if nums[mid] >= nums[l]: if nums[l]<=target<nums[mid]: r = mid - 1 else: l = mid + 1 else: if nums[mid]<target<=nums[r]: l = mid + 1 else: r = mid - 1 return -1