Skip to content

Commit f1e45b7

Browse files
committed
search in rotated sorted array
1 parent 2a9a1c9 commit f1e45b7

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Solution {
2+
public int search(int[] nums, int target) {
3+
int firstIdx = binarySearch(nums);
4+
int result = 0;
5+
if (firstIdx == 0) {
6+
return binarySearch(target, nums, 0, nums.length - 1);
7+
} else if (target >= nums[0]) {
8+
return binarySearch(target, nums, 0, firstIdx);
9+
} else {
10+
return binarySearch(target, nums, firstIdx, nums.length - 1);
11+
}
12+
}
13+
14+
public int binarySearch(int[] nums) {
15+
int start = 0;
16+
int end = nums.length -1;
17+
while(start < end) {
18+
int mid = (start + end) / 2;
19+
if(nums[mid] < nums[end]) {
20+
end = mid;
21+
} else {
22+
start = mid + 1;
23+
}
24+
}
25+
return start;
26+
}
27+
28+
public int binarySearch(int target, int[] nums, int start, int end) {
29+
int result = -1;
30+
while(start <= end) {
31+
int mid = (start + end) / 2;
32+
if(nums[mid] > target) {
33+
end = mid - 1;
34+
} else if(nums[mid] < target){
35+
start = mid + 1;
36+
} else {
37+
result = mid;
38+
break;
39+
}
40+
}
41+
42+
return result;
43+
}
44+
45+
46+
}

0 commit comments

Comments
 (0)