Search in Rotated Sorted Array

来源:互联网 发布:专业处理淘宝盗图申诉 编辑:程序博客网 时间:2024/06/14 19:13

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.


class Solution:    # @param A, a list of integers    # @param target, an integer to be searched    # @return an integer    def search(self, A, target):        if 0 == len(A):            return -1        minx = self.__findMin(A)        if target < A[minx] or target > A[minx - 1]:            return -1        rslt = 0        if target >= A[minx] and target <= A[-1]:            rslt = self.binsearch(A[minx:], target)            if -1 == rslt:                return -1            rslt += minx        else:            rslt = self.binsearch(A[:minx], target)        return rslt    def binsearch(self, array, target):        if 0 == len(array):            return -1        mid = len(array) / 2        if target == array[mid]:            return mid        elif len(array) > 1:            if target < array[mid]:                return self.binsearch(array[:mid], target)            else:                rslt = self.binsearch(array[mid:], target)                if -1 == rslt:                    return -1                return mid + rslt        else:            return -1    def __findMin(self, num):        if num[-1] >= num[0]:            return 0        mid = len(num) / 2        if num[mid] < num[0]:            return 1 + self.__findMin(num[1:mid+1])        else:            return mid + 1 + self.__findMin(num[mid+1:])s = Solution()arr = [5,1,3]#print s.search(arr, 2)print s.binsearch(arr, 2)


0 0
原创粉丝点击