分类:Array
考察知识点:Array(数组遍历) 二分法
最优解时间复杂度:O(logn)
33. 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).
Example1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
代码:
我的Python取巧解法:
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
#就4行,简单到你想笑晕在厕所
try:
return nums.index(target)
except:
return -1
正常解法
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
#判定边界条件
if len(nums)==0:
return -1
start=0
end=len(nums)-1
while(end>start+1):
#判定是end>start+1!!!
mid=(end-start)//2+start
if nums[mid]==target:
return mid
if(nums[start]<nums[mid]):
#说明左边单调递增
if nums[start]<=target and target<=nums[mid]:
end=mid
else:
start=mid
else:
#说明右边单调递增
if nums[mid]<=target and target<=nums[end]:
start=mid
else:
end=mid
if nums[start]==target:
return start
elif nums[end]==target:
return end
else:
return -1
讨论:
1.看到O(logn)的时间复杂度,没有什么可说,就是用两个指针然后2分法
2.用Python自带的方法时间复杂度是O(n),所以慢,但是写起来真的超级简单
3.start+1<end是这个判定条件,不是别的,千万别写错了