美文网首页
[Med Bi-Div] 33. Search in Rotat

[Med Bi-Div] 33. Search in Rotat

作者: Mree111 | 来源:发表于2019-10-21 10:55 被阅读0次

    Description

    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

    (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

    You are given a target value to search. If found in the array return its index, otherwise return -1.

    You may assume no duplicate exists in the array.

    Your algorithm's runtime complexity must be in the order of O(log n).

    Solution

    二分法,分情况处理
    (类似题目:找min)

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

    相关文章

      网友评论

          本文标题:[Med Bi-Div] 33. Search in Rotat

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