Description
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
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
Submissions
首先根据复杂度要求可以想到二分法,其次已知条件列表是一个升序列表从某位置旋转处理过的。所以这道题的解题思路是先判断列表是否为空,若是则直接返回-1,之后初始化l,r 为列表的两端,mid为中间位置,如果中间位置是target则直接返回mid,若不是则判断target在左半部分还是右半部分,并调整l,r .若循环遍历结束未找到target,则返回-1。
实现代码如下:
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+1)//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