[算法题] Search in Rotated Sorted Array

时间:2022-06-07 08:46:32

题目内容

本题来源LeetCode

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.

题目思路

题目难度:medium

这个题目是对常规的二分查找的一个变形。基本的思路就是用二分查找。但是区别在于:二分查找进行二分的条件是判断target和nums[mid]之间的大小;而这里进行二分的条件是更加复杂,不仅需要判断nums[mid]在数组的左半部分还是右半部分,而且要判断target和子数组两端元素的关系。

另外,此题的难点在于边界条件的把握,什么时候取等号需要认真考虑。

Python代码

class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if nums==[]:
return -1
end=len(nums)-1
start=0
while start<=end:
mid=(start+end)/2
if nums[mid]==target:
return mid
if nums[mid]>=nums[start]:
if nums[start]<=target and target<nums[mid]:
end=mid
else:
start=mid+1
else:
if nums[end]>=target and nums[mid]<target:
start=mid+1
else:
end=mid
return -1