33. Search in Rotated Sorted Array
problem description
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:
Example 2:
algorithm thought
其实是二分查考的变种,一个有序数组,rotate之后数组一半还是顺序的。二分查找只要确定一半是否满足 就可以排除另一半。我们找到有序的一半之后,判断target是否期中,如果是就进入这一半查找否则进入另一半。这样每次排除一半,时间复杂度就是O(nlgn)
code
algorithm thought
虽然循环中间处理比二分查找多很多步骤,但是时间复杂度还是O(1)的。每次排除一半,最后时间复杂度是O(nlgn)
Previous32. Longest Valid ParenthesesNext34. Find First and Last Position of Element in Sorted Array
Last updated