码迷,mamicode.com
首页 > 其他好文 > 详细

33. Search in Rotated Sorted Array

时间:2017-07-11 12:17:20      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:pivot   code   turn   value   strong   https   arch   ref   ges   

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

 

33. Search in Rotated Sorted Array

标签:pivot   code   turn   value   strong   https   arch   ref   ges   

原文地址:http://www.cnblogs.com/prmlab/p/7149899.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!