搜索旋转排序数组(LeetCode)
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组
[0,1,2,4,5,6,7]可能变为
[4,5,6,7,0,1,2])。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回
-1。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
示例 1:
输入: nums = [[code]4,5,6,7,0,1,2], target = 0 输出: 4 [/code]
示例 2:
输入: nums = [[code]4,5,6,7,0,1,2], target = 3 输出: -1[/code]
'''
这道题的难点在于时间复杂度的限制。
O(logn)嘛,显然是二分查找的变种。
所以就要找缩小范围的条件。
这种题真的
'''
class Solution:
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)//2
if nums[low] == target:return low#总觉得边界会被略过,所以手残比较了三个边界
if nums[mid] == target:return mid
if nums[high] == target:return high
if nums[mid] < nums[high]:#右半边的数组有序有序
if target < nums[high] and target > nums[mid]:#target在右半边
low = mid + 1#把范围缩到右半边
else:#target不在右半边
high = mid - 1
else:#左半边的数组有序
if target < nums[mid] and target > nums[low]:#target在左半边
high = mid - 1#把范围缩到左半边
else:#target不在左半边
low = mid + 1
return -1#找不着,返回-1
- Leetcode 81 搜索旋转排序数组 II Python C++ 史上最详细题解系列
- LeetCode——旋转排序数组搜索
- 搜索旋转排序数组 - LeetCode
- 33. 搜索旋转排序数组Leetcode
- leetcode33_搜索旋转排序数组
- Leetcode 33. 搜索旋转排序数组
- leetcode 33. 搜索旋转排序数组
- 【LeetCode-面试算法经典-Java实现】【081-Search in Rotated Sorted Array II(搜索旋转的排序数组)】
- LeetCode 33 Search in Rotated Sorted Array(在旋转排序数组中搜索)(*)
- LeetCode 81. Search in Rotated Sorted Array II(搜索旋转的数组)
- 线性表--搜索旋转排序数组 II(Search in Rotated Sorted Array II)
- LeetCode 153. 寻找旋转排序数组中的最小值 Python
- LintCode:搜索旋转排序数组 II
- 在旋转排序数组中搜索
- 【leetcode】有重复的旋转排序数组查找(二分)
- 63 - 搜索旋转排序数组 II
- leetcode 6. 在有序数组旋转后搜索 Search in Rotated Sorted Array
- LintCode 62 搜索旋转排序数组
- LintCode:M-搜索旋转排序数组
- LintCode-搜索旋转排序数组