LeetCode 33. Search in Rotated Sorted Array

题目描述

There is an integer array nums sorted in ascending order (with distinct values).

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

You must write an algorithm with O(log n) runtime complexity.

解题思路

看到 O(log n) 的时间复杂度,第一时间想到二分查找。但是给出的列表是局部有序的,我们就需要改变传统的二分的思路。
直接看代码。

代码 (Python 3)

class Solution:
    def search(self, nums, target: int) -> int:
        if target not in nums:
            return -1
        left = 0
        right = len(nums) - 1
        while left <= right:  # 开始二分查找
            mid = (left + right) // 2
            if nums[mid] == target:  # 找到即退出
                return mid
            elif nums[mid] >= nums[left]: # 关键!若此条件满足,则在 [left, mid] 区间为单调
                if nums[left] <= target <= nums[mid]:
                    right = mid
                else:
                    left = mid + 1
            else: 
                if nums[mid] < target <= nums[right]:
                    left = mid + 1
                else:
                    right = mid - 1
        return -1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值