假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
示例 1:
输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
示例 2:
输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1
直接使用二分类查找 target 位置,先确定 target 在数组左边还是右边,在进行范围减小搜索,直到找到 target 位置。
import bisect
bisect.bisect_left(t,x) #在T列表中查找x,若存在,返回x左侧位置
bisect.bisect_right(t,x)
bisect.insort_left(t,x) #在T列表中查找X,若存在,插入x左侧;
bisect.insort_right(t,x)
下面是其实现的方法,实际是二分法:
def binary_search(t,x):
temp = t;
temp.sort();
low = 0;
mid = 0;
high = len(temp)-1;
while low < high:
mid = (low+high)/2;
if xt[mid]:
low = mid+1;
else:
return mid-1; #是否等价与bisect_left;
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 = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[left] <= nums[mid]:
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
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
n = len(nums)
left = 0
right = len(nums)-1
while left < right:
mid = (left+right)//2
if nums[right] < nums[mid]:
left = mid + 1
else:
right = mid
t = left
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
realmid = (mid+t)%n
if nums[realmid] == target:
return realmid
elif nums[realmid] < target:
left = mid+1
else:
right = mid-1
return -1
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return nums.index(target)
else:
return -1
class Solution:
def search(self, nums: List[int], target: int) -> int:
def half_search(nums, target, i, j, head):
mid = int(0.5 * (j + i))
if i > j:
return -1
if nums[mid] == target:
return mid
if (nums[mid] < target < head) or (head <= nums[mid] < target) or (nums[mid] >= head and target < head):
return half_search(nums, target, mid + 1, j, head)
else:
return half_search(nums, target, i, mid-1, head)
if not nums:
return -1
head = nums[0]
return half_search(nums, target, 0, len(nums) - 1, head)