【leetcode】33. Search in Rotated Sorted Array

题目如下:

解题思路:题目要求时间复杂度是O(log n),而且数组也是有序的,那么可以考虑采用二分查找法。那么解题的关键就是找出转折点,找到了转折点后,把数组拆分成两段,再分别用二分查找,即可得到答案。

代码如下:

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if len(nums) == 0:
            return -1
        split = 0
        for i in xrange(len(nums)-1):
            if nums[i] > nums[i+1]:
                split = i + 1
                break

        import  bisect
        #print nums[:split]
        res = bisect.bisect_left(nums[:split],target)
        #print res
        if res < len(nums[:split]) and nums[:split][res] == target:
            return res

        res = bisect.bisect_left(nums[split:], target)
        #print nums[split:]
        #print res
        if res < len(nums[split:]) and nums[split:][res] == target:
            return res + split
        return -1

 

posted @ 2018-05-05 20:29  seyjs  阅读(152)  评论(0编辑  收藏  举报