Search in Rotated Sorted Array

来源:互联网 发布:mac电脑的使用教程 编辑:程序博客网 时间:2024/06/05 01:01

leetcode第33题,要求在一个旋转后的有序数组中找出目标数字。

所谓旋转,指的就是,在某处断开数组,从这一点前面是一个升序排列的数组,后面也是。

不难想到用二分查找,我的做法是,先找出分界点,这样这个问题就被转化为两个有序数组的查找问题,直接应用二分查找即可。

class Solution(object):    def search(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: int        """        def binarySearch(nums, start, end):            while start <= end and start >= 0 and end < len(nums):                mid = (start + end) / 2                if nums[mid] > target:                    end = mid-1                elif nums[mid] < target:                    start = mid+1                else:                    return mid            else:                return -1        n = len(nums)        if n == 0:            return -1        axis = 0        for i in range(1, n):            if nums[i-1] > nums[i]:                axis = i-1                break        ans = binarySearch(nums, 0, axis)        ans2 = binarySearch(nums, axis+1, n-1)        print ans, ans2        if ans != -1:            return ans        elif ans2 != -1:            return ans2        else:            return -1
0 0
原创粉丝点击