题目描述:
题解:
1.根据时间复杂度要求确定采用二分法。
2.首先应该确定旋转点位置,旋转点之前和之后的两段数组均有序。
3.找到旋转点之后,在前后两端分别再用二分法查找target。更简单的方法是:先判断target会出现在旋转点之前还是之后的数组,只在一段数组内进行二分查找。
class Solution(object): def search(self, nums, target): if len(nums)==1: if nums[0]==target: return 0 else: return -1 left = 0 right = len(nums)-1 while left<=right: mid = (left+right)//2 print(left,right,mid) if nums[mid]<nums[mid-1]: left=mid break elif nums[mid]>nums[right]: left = mid+1 else: right = mid-1 print(left,right) nums1 = nums[0:left] nums2 = nums[left:len(nums)] res1 = -1 res2 = -1 if len(nums1)>0: res1= self.bin_search(nums1,target) if res1!=-1: return res1 else: if len(nums2)>0: res2 = self.bin_search(nums2,target) if res2!=-1: return res2+left return -1 def bin_search(self, nums, target): left = 0 right = len(nums)-1 mid = 0 while left<=right: mid = (left+right)//2 if nums[left]==target: return left if nums[right]==target: return right if nums[mid]==target: return mid if nums[mid]<target: left = mid+1 if nums[mid]>target: right = mid-1 if nums[mid]==target: return mid else: return -1
2021.11.17
发现一个更简单的方法,参考:
不是先找到旋转点再搜索,而是一边判断左右两段哪段有序,一边搜索,搜索的同时舍弃target不在的半段。
class Solution(object): def search(self, nums, target): left = 0 right = len(nums)-1 while(left<right): mid = int(left+(right-left+1)/2) if nums[mid]<nums[right]: if target<=nums[right] and target>=nums[mid]: left=mid else: right=mid-1 else: if target<=nums[mid-1] and target>=nums[left]: right = mid-1 else: left=mid if target==nums[left]: return left return -1