033 Search in Rotated Sorted Array

这道题比较a[start] 和 a[half]的值就可以判断 该序列的头在左半部分 还是右半部分,这样就可以利用二分查找了

class Solution:
    # @param A, a list of integers
    # @param target, an integer to be searched
    # @return an integer
    def search(self, A, target):
        if len(A) == 0:
            return -1
        return self.solve(A, target, 0, len(A)- 1)

    def solve(self, a, target, start, end):
        if start > end:
            return -1
        half = int((end-start)/2) + start
        if a[start] == target:
            return start
        if a[end] == target:
            return end
        if a[half] == target:
            return half
        if a[start] < a[half]:
            if target > a[half] or target < a[start]:
                return self.solve(a, target, half+1, end-1)
            else:
                return self.solve(a, target, start+1, half-1)
        else:
            if target < a[half] or target > a[start]:
                return self.solve(a, target, start+1, half-1)
            else:
                return self.solve(a, target, half+1, end-1)

 

posted @ 2015-07-08 12:27  dapanshe  阅读(160)  评论(0编辑  收藏  举报