Problem
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:
1 |
|
Example 2:
1 |
|
Explanation
-
For example, the array is [3, 4, 5, 6, 7, 8, 9, 1, 2], the middle element is 7. We can draw the graph like below:
1
2
3
4
5
6
7
8
9/ / /(mid) / / / /(left = 3) /(right = 2) /
-
We need to consider two cases, case1, the
mid
is greater thanleft
, case2 is themid
is less thanleft
. The above example is case1. In case1, if thetarget
is greater thanleft
andtarget
is less thanmid
, then we can setright = mid
, else, we setleft = mid
. Then, we recusivly find themid
and check again. In case2, iftarget
is less thanright
andtarget
is greater thanmid
, then we can setleft = mid
, else, we setright = mid
. Then, we also recursivly find themid
and check again. -
When the
left
andright
is next to each other, we can break out the loop, and checkleft
andright
individually. If not found thetarget
, we return -1.
Solution 1
1 |
|
Solution 2
1 |
|