Skip to content

Commit 29e93bb

Browse files
Create 42 Search in a rotated sorted array.java
1 parent c607b4e commit 29e93bb

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
//O(logn) time and O(1) space
2+
class Solution {
3+
public int search(int[] nums, int target) {
4+
//Find the original low
5+
int low = 0,high = nums.length-1;
6+
while(low<high){
7+
int mid = low+(high-low)/2;
8+
if(nums[mid]>nums[high])
9+
low = mid+1;
10+
else high = mid;
11+
}
12+
//Now low and high has the same value which is equal to the index of the smallest element in the array
13+
int rot = low;
14+
low=0;
15+
high = nums.length-1;
16+
while(low<=high){
17+
int mid = low+(high-low)/2;
18+
int realmid = (mid+rot)%nums.length;
19+
if(nums[realmid]==target) return realmid;
20+
else if(nums[realmid]>target) high = mid-1;
21+
else low = mid+1;
22+
}
23+
return -1;
24+
}
25+
}

0 commit comments

Comments
 (0)