33. 旋转数组查找target

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        # 思路: 二分法
        # 1.判断左边的数组是是非递减还是右边的数组是非递减的
        # 2.判断target是否在非递减的数组内,
        # 3.在非递减的数组内判断时,注意数组长度有可能为1,所以要判断边界是否等于target
        # 4.其他方法和二分法一致即可

        left = 0
        right = len(nums) - 1
        while left <= right:
            mid = left + (right - left) // 2
            if nums[mid] == target:
                return mid
            if nums[left] <= nums[mid]:
                if nums[left] == target:
                    return left
                if nums[left] < target < nums[mid]:
                    right = mid - 1
                else:
                    left = mid + 1
            elif nums[mid] <= nums[right]:
                if nums[right] == target:
                    return right
                if nums[mid] < target < nums[right]:
                    left = mid + 1
                else:
                    right = mid - 1
        return -1

s = Solution()
res = s.search([3,1],3)
print(res)

你可能感兴趣的:(33. 旋转数组查找target)