【leetcode】33. Search in Rotated Sorted Array

The topics are as follows:

Problem- solving ideas : The problem requires that the time complexity is O (log  n ), and the array is also ordered, then the binary search method can be considered. Then the key to solving the problem is to find the turning point. After finding the turning point, split the array into two sections, and then use binary search respectively to get the answer.

code show as below:

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

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325343917&siteId=291194637