https://leetcode-cn.com/problems/search-in-rotated-sorted-array/
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
示例 1:
输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
示例 2:
输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1
和之前寻找排序数组中得最小值类似,用二分法。如果左边有序且要找得值在左边,那么让right=mid-1,否则left=mid+1;若右边有序且要找得值在右边,那么让left=mid+1,否则right=mid-1。注意这次得while条件是left<=right,若是<,则最后还要判断nums[left]与target的关系。
class Solution:
def search(self, nums, target):
\"\"\"
:type nums: List[int]
:type target: int
:rtype: int
\"\"\"
left, right = 0, len(nums)-1
while left <= right:
mid = (left+right)//2
if nums[mid] == target:
return mid
if nums[mid] > nums[right]: # 左边有序
if nums[mid] > target and nums[left] <= target:
right = mid - 1
else:
left = mid + 1
else: # 右边有序
if nums[mid] < target and nums[right] >= target:
left = mid + 1
else:
right = mid - 1
return -1
继续阅读与本文标签相同的文章
上一篇 :
多尺度的图像细节提升
下一篇 :
特斯拉在第三季度财报电话会议上没有谈到的三件事
-
特斯拉自动驾驶系统涨价遭质疑 马斯克:我们不能一直亏钱
2026-05-14栏目: 教程
-
首个二类资源区平价光伏电站正式并网发电
2026-05-14栏目: 教程
-
AI+5G科技创新 视频行业呈现轻应用化趋势
2026-05-14栏目: 教程
-
1.98亿滴滴用户添加了紧急联系人 每天百万个订单行程分享给亲友
2026-05-14栏目: 教程
-
工程院院士刘韵洁:5G前景很大,但主要是行业应用
2026-05-14栏目: 教程
