Skip to content

Commit 532fde2

Browse files
authored
Create Search in Rotated Sorted Array.java
1 parent b63c2a9 commit 532fde2

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
}

0 commit comments

Comments
 (0)