forked from super30admin/Binary-Search-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem1Solution.java
More file actions
30 lines (29 loc) · 848 Bytes
/
problem1Solution.java
File metadata and controls
30 lines (29 loc) · 848 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//Time Complexity : O(log n)
//Space Complexity : O(1)
//Search in a Rotated Sorted Array
public class problem1Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length-1;
while(left<=right){
int mid = left + (right - left)/2;
if(nums[mid]== target) return mid;
if(nums[left]<=nums[mid]) {
if (target > nums[mid] || target < nums[left] )
left = mid + 1;
else {
right = mid -1;
}
}
else {
if( target < nums[mid] || target > nums[right]){
right = mid - 1;
}
else {
left = mid + 1;
}
}
}
return -1;
}
}