Search in Rotated Sorted Array

Suppose a sorted array 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.

这题需要在旋转数组中查找target,返回index.因为本身是有序数组,且没有重复数字.所以右边一段在左边这段的所有元素下面.

如果二分遇到某段包含pivot的元素在,则无法判断这一段的最低值.但是没关系,二分的关键在于去掉不可能的一半,所以我们可以利用有序的那一半:

1.如果在有序区间内,则在有序区间内继续查找.

2.如果不在有序区间内,则在另外一段无序区间内继续查找.

代码如下:

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if not nums:
            return -1
        l = 0 
        r = len(nums)-1
        while l + 1 < r:
            mid = l + (r-l)/2
            if nums[mid] == target:
                return mid
            if nums[mid] > nums[l]:
                if  nums[l] <= target < nums[mid]:
                    r = mid
                else:
                    l = mid
            else:
                if nums[mid] < target <= nums[r]:
                    l = mid
                else:
                    r = mid
        if nums[l] == target:
            return l
        elif nums[r] == target:
            return r
        else:
            return -1

 

转载于:https://www.cnblogs.com/sherylwang/p/5496566.html

你可能感兴趣的:(Search in Rotated Sorted Array)