website/content/ChapterFour/0001~0099/0033.Search-in-Rotated-Sorted-Array.md
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
假设按照升序排序的数组在预先未知的某个点上进行了旋转。( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
nums[mid] > nums[low],如果是落在后面一段数值比较小的区间内,nums[mid] ≤ nums[low] 。如果 mid 落在了后一段数值比较小的区间内了,那么一定有 nums[mid] < nums[high],如果是落在前面一段数值比较大的区间内,nums[mid] ≤ nums[high] 。还有 nums[low] == nums[mid] 和 nums[high] == nums[mid] 的情况,单独处理即可。最后找到则输出 mid,没有找到则输出 -1 。
package leetcode
func search33(nums []int, target int) int {
if len(nums) == 0 {
return -1
}
low, high := 0, len(nums)-1
for low <= high {
mid := low + (high-low)>>1
if nums[mid] == target {
return mid
} else if nums[mid] > nums[low] { // 在数值大的一部分区间里
if nums[low] <= target && target < nums[mid] {
high = mid - 1
} else {
low = mid + 1
}
} else if nums[mid] < nums[high] { // 在数值小的一部分区间里
if nums[mid] < target && target <= nums[high] {
low = mid + 1
} else {
high = mid - 1
}
} else {
if nums[low] == nums[mid] {
low++
}
if nums[high] == nums[mid] {
high--
}
}
}
return -1
}