leetcode-33-搜索旋转排序数组

题目描述:

方法一:

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        def half_search(nums,target,i,j,head):
            mid = int(0.5*(j+i))
            if i>j:
                return -1
            if nums[mid] == target:
                return mid
            
            if (nums[mid]<target<head) or (head<=nums[mid]<target) or (nums[mid] >= head and target <head):
                return half_search(nums,target,mid+1,j,head)
            else:
                return half_search(nums,target,i,mid-1,head)
        if not nums:
            return -1
        return half_search(nums,target,0,len(nums)-1,nums[0])

 另:

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

 

posted @ 2019-07-10 17:27  oldby  阅读(123)  评论(0编辑  收藏  举报