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
midis greater thanleft, case2 is themidis less thanleft. The above example is case1. In case1, if thetargetis greater thanleftandtargetis less thanmid, then we can setright = mid, else, we setleft = mid. Then, we recusivly find themidand check again. In case2, iftargetis less thanrightandtargetis greater thanmid, then we can setleft = mid, else, we setright = mid. Then, we also recursivly find themidand check again. -
When the
leftandrightis next to each other, we can break out the loop, and checkleftandrightindividually. If not found thetarget, we return -1.
Solution 1
1 | |
Solution 2
1 | |