File tree 1 file changed +26
-0
lines changed
1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int search (int [] A , int target ) {
3
+ int n = A .length ;
4
+ int lo =0 ,hi =n -1 ;
5
+ // find the index of the smallest value using binary search.
6
+ // Loop will terminate since mid < hi, and lo or hi will shrink by at least 1.
7
+ // Proof by contradiction that mid < hi: if mid==hi, then lo==hi and loop would have been terminated.
8
+ while (lo <hi ){
9
+ int mid =(lo +hi )/2 ;
10
+ if (A [mid ]>A [hi ]) lo =mid +1 ;
11
+ else hi =mid ;
12
+ }
13
+ // lo==hi is the index of the smallest value and also the number of places rotated.
14
+ int rot =lo ;
15
+ lo =0 ;hi =n -1 ;
16
+ // The usual binary search and accounting for rotation.
17
+ while (lo <=hi ){
18
+ int mid =(lo +hi )/2 ;
19
+ int realmid =(mid +rot )%n ;
20
+ if (A [realmid ]==target )return realmid ;
21
+ if (A [realmid ]<target )lo =mid +1 ;
22
+ else hi =mid -1 ;
23
+ }
24
+ return -1 ;
25
+ }
26
+ }
You can’t perform that action at this time.
0 commit comments