LeetCode33 搜索旋转排序数组(二分)

LeetCode33 搜索旋转排序数组

二分数列,仅仅当对于当前处理部分nums[l] < target < nums[r]时,进行答案更新,否则在另一部分寻找答案

class Solution:
    def search(self, nums: List[int], target: int) -> int:

        l, r, poc = 0, len(nums) - 1, -1

        while l <= r:

            mid = (l + r) // 2
            # print(l, r, mid)

            if nums[l] <= nums[mid]:
                
                if nums[mid] >= target and nums[l] <= target: poc, r = mid, mid - 1
                else: l = mid + 1

            else:
                if nums[mid] <= target and nums[r] >= target: poc, l = mid, mid + 1
                else: r = mid - 1

        if nums[poc] == target: return poc
        else: return -1

posted on 2022-07-02 14:35  solvit  阅读(16)  评论(0编辑  收藏  举报

导航