【LeetCode】33. Search in Rotated Sorted Array 解题记录
问题描述
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
测试样例
1 | Input: nums = [4,5,6,7,0,1,2], target = 0 |
1 | Input: nums = [4,5,6,7,0,1,2], target = 3 |
1 | Input: nums = [1], target = 0 |
说明
1 | 1 <= nums.length <= 5000 |
解题
思路
使用二分法,重点在于如何确定该向哪一侧递归。
判断 nums[left]
和 nums[mid]
的相对大小:
-
若
left
值大于mid
值,则前半部分非递增,后半部分有序- 根据目标是否在有序一侧,缩小范围(
nums[mid] <= target && target <= nums[r]
)
- 根据目标是否在有序一侧,缩小范围(
-
若 left 值小于 mid 值,则后半部分非递增,前半部分有序
- 根据目标是否在有序一侧,缩小范围(
nums[l] <= target && target <= nums[mid]
)
- 根据目标是否在有序一侧,缩小范围(
-
若两值相等,则无法判断哪侧有序
- 令左边界右移一位(
left
值和mid
值相等,舍弃left
值还有mid
值,不影响结果)
- 令左边界右移一位(
补充:
- 时间复杂度
O(logn)
代码
1 | class Solution { |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 哆啦 C 梦!
评论