美文网首页
[Leetcode] 33. 搜索旋转排序数组

[Leetcode] 33. 搜索旋转排序数组

作者: 丶噗噗噗噗噗 | 来源:发表于2020-04-27 21:16 被阅读0次

    33. 搜索旋转排序数组

    来源: 33. 搜索旋转排序数组

    1. 解题思路

    二分法查找

    2. 代码

    class Solution:
        def search(self, nums: List[int], target: int) -> int:
            if len(nums) == 0:
                return -1
            left, right = 0, len(nums)-1
            while left + 1 < right:
                mid = (left + right) // 2
                if nums[mid] == target:
                    return mid
                if nums[left] < nums[mid]:
                    if nums[left] <= target and target <= nums[mid]:
                        right = mid
                    else:
                        left = mid
                else:
                    if nums[mid] <= target and target <= nums[right]:
                        left = mid
                    else:
                        right = mid
            if nums[left] == target:
                return left
            if nums[right] == target:
                return right
            return -1
    

    相关文章

      网友评论

          本文标题:[Leetcode] 33. 搜索旋转排序数组

          本文链接:https://www.haomeiwen.com/subject/ttcpwhtx.html