题目描述(中等难度)
解题思路
这道题属于二分查找的变形
python 代码
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
left = 0
right = len(nums) - 1
while left <= right:
mid = (right + left) // 2
if nums[mid] == target:
return mid
if nums[mid] >= nums[left]: # 左边升序
# 如果不限定左边的界限,就会出现0<7,从而找不到此值,而真实结果是存在的
if nums[left] <= target <= nums[mid]: # 在左边范围内
right = mid - 1
else: # 只能从右边找
left = mid + 1
else: # 右边升序
if nums[mid] <= target <= nums[right]: # 在右边范围内
left = mid + 1
else: # 只能从左边找
right = mid - 1
return -1 # 没找到
s = Solution()
res = s.search([4, 5, 6, 7, 0, 1, 2], 0)
print('.....',res) # 4