LeetCode---33. Search in Rotated Sorted Array

题目

给出一个递增有序数组,以某个元素为准旋转,如[0,1,2,4,5,6,7]变成了[4,5,6,7,0,1,2]。另给出一个目标值,在这个数组中寻找,如果找到返回index,否则返回-1。数组中没有重复元素,你的算法时间复杂度必须为O(logn)。

Python题解

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        low, high = 0, len(nums) - 1
        while low <= high:
            mid = low + (high - low + 1) // 2
            if nums[mid] == target:
                return mid
            if nums[low] <= nums[mid]:
                if nums[low] <= target <= nums[mid]:
                    high = mid - 1
                else:
                    low = mid + 1
            else:
                if nums[mid] <= target <= nums[high]:
                    low = mid + 1
                else:
                    high = mid - 1
        return -1

猜你喜欢

转载自blog.csdn.net/leel0330/article/details/80483785