Search in Rotated Array: Given a sorted array of n
integers that has been rotated an unknown number of times, write code to find an element in the array. You may assume that the array was originally sorted in increasing order.
EXAMPLE
|
|
Hints: #298, #310
解法1
你可以认为在一个循环有序数组里查找。
把这个数组中间切一刀,那么会发现左右两边至少会有一边是有序的(头 < 尾)。我们在有序的里面二分查找,在无需的那么在另一边里再切一刀找。
步骤:
- 把数组中间切一刀,会得到L、R两个数组
- 如果某个数组的头 < 尾,说明它是有序的,启用二分查找
- 如果某个数组的头 >= 尾,说明它是无序的,对它重复1-3步
|
|
时间复杂度:
- 如果本来就是有序的,复杂度是O(log n),和二分一样
- 如果全部都是重复元素,复杂度O(n),比如在
[3,3,3,3]
里找2
,那么最终会对4个3
做二分。
评论