![924f41477714051ccd556bb66a31d8b0.png](https://i-blog.csdnimg.cn/blog_migrate/b9e8703407cc4cded838d84e0fc869b9.jpeg)
给你一个升序排列的整数数组 nums
,和一个整数 target
。
假设按照升序排序的数组在预先未知的某个点上进行了旋转。(例如,数组 [0,1,2,4,5,6,7]
可能变为 [4,5,6,7,0,1,2]
)。
请你在数组中搜索 target
,如果数组中存在这个目标值,则返回它的索引,否则返回 -1
。
示例 1:
输入:nums = [4,5,6,7,0,1,2], target = 0
输出:4
示例 2:
输入:nums = [4,5,6,7,0,1,2], target = 3
输出:-1
示例 3:
输入:nums = [1], target = 0
输出:-1
提示:
1 <= nums.length <= 5000
-10^4 <= nums[i] <= 10^4
nums
中的每个值都 独一无二nums
肯定会在某个点上旋转-10^4 <= target <= 10^4
#
# @lc app=leetcode.cn id=33 lang=python3
#
# [33] 搜索旋转排序数组
#
# @lc code=start
class Solution:
def search(self, nums: List[int], target: int) -> int:
n = len(nums)
l,r = 0,n-1
while(l<=r):
mid=(r-l)>>1
mid+=l
if target==nums[mid]:
return mid
if nums[mid]>=nums[0]:
if target>nums[mid] or target<nums[0]:
l=mid+1
elif target<nums[mid] and target>=nums[0]:
r=mid-1
elif nums[mid]<nums[0]:
if target<nums[mid] or target>nums[n-1]:
r=mid-1
elif target>nums[mid] and target<=nums[n-1]:
l=mid+1
return -1
# @lc code=end