leetcode33. Search in Rotated Sorted Array
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
大意原有一个排序好的严格单调增整数序列,将其旋转,
也就是说旋转以后的序列可能是一段增序列,也有可能是由两段增序列组成,并且第二段序列中的任意数字小于第一段序列中的任意数字
然后在那之中找到目标数的索引,找不到就返回-1,要求时间复杂度是O(log n)
初步的想法是
1,先找到转折点,所谓转折点就是第一段序列的最后一个数字,O(log n)复杂度,类似于二分查找
2,从而确定target所在的递增序列,
3, 寻找符合的数字,logn复杂度,
这样做下来时间复杂度是没有问题的,就是所花时间太长了,然后借鉴了别人的代码,自己写了一下
class Solution: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ m, n = 0, len(nums)-1 while(m<=n): mid = (m+n)//2 if nums[mid] == target: return mid #这个地方要注意界限的判断因为mid是可以=m的 #mid位于前半段 if nums[mid] >= nums[m]: #因为m-mid是递增的判断target是否处于该范围 if target < nums[mid] and target >= nums[m]: n = mid - 1 else: m = mid + 1 #位于后半段 else: #因为mid-n是递增的判断target是否处于该范围 if target > nums[mid] and target <= nums[n]: m = mid + 1 else: n = mid - 1 return -1
二分查找的变种,尤其要注意的就是边界的问题,