33. Search in Rotated Sorted Array

https://leetcode.com/problems/search-in-rotated-sorted-array/#/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.

Sol :

A sorted array is rotated. It must be one of the two conditions.

[6,7,1,2,3,4,5]

 

Figure 1

[3,4,5,6,7,1,2]

Figure 2

According to two figures above, if A[left] <= A[mid] then [left, mid] must be an ascending array. 

We are going to implement it using binary search.

 

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        
        # binary search  
        first = 0
        last = len(nums) - 1
        while first <= last:
            mid = (last+first)/2
            if nums[mid] == target:
                return mid
            # See figure 2
            if nums[first] <= nums[mid]:
                if nums[first] <= target < nums[mid]:
                    last = mid - 1
                else:
                    first = mid + 1
            # see figure 1
            else:
                if nums[mid] < target <= nums[last]:
                    first = mid + 1
                else:
                    last = mid - 1
       
        return -1
原文地址:https://www.cnblogs.com/prmlab/p/7149899.html