-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearch in Rotated Sorted Array
55 lines (51 loc) · 1.46 KB
/
Search in Rotated Sorted Array
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
public int search(int[] nums, int target) {
//min will have index of minimum element of nums
int min = minserach(nums);
//find in sorted left
if(nums[min] <= target && target <= nums[nums.length-1]){
return search(nums,min,nums.length-1,target);
}
//find in sorted right
else{
return search(nums,0,min,target);
}
}
//binary search to find target in left to right boundary
public int search(int[] nums,int left,int right,int target){
int l = left;
int r = right;
// System.out.println(left+" "+right);
while(l <= r){
int mid = l + (r - l)/2;
if(nums[mid] == target){
return mid;
}
else if(nums[mid] > target){
r = mid-1;
}
else{
l = mid+1;
}
}
return -1;
}
//smallest element index
public int minserach(int[] nums){
int left = 0;
int right = nums.length-1;
while(left < right){
int mid = left + (right - left)/2;
if(mid > 0 && nums[mid-1] > nums[mid]){
return mid;
}
else if(nums[left] <= nums[mid] && nums[mid] > nums[right]){
left = mid+1;
}
else{
right = mid-1;
}
}
return left;
}
}