forked from Suman21/Interviewbit-Solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearch in Rotated Sorted Array
42 lines (38 loc) · 1009 Bytes
/
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
class Solution {
public int find(int []nums,int target,int s,int e)
{
int m=(s+e)/2;
if(s>e || m>=nums.length)
return -1;
if(nums[m]==target)
return m;
if(nums[m]>target)
return find(nums,target,s,m-1);
else
return find(nums,target,m+1,e);
}
public int search(int[] nums, int target) {
if(nums.length==0)
return -1;
int ans=-1,s=0,e=nums.length,m=-1;
if(nums[0]==target)
return 0;
while(e>s)
{
m=(s+e)/2;
if(m+1<nums.length && nums[m]>nums[m+1])
{ ans=m;
break;
}
else if(nums[m]>nums[0])
s=m+1;
else
e=m;
}
System.out.println(m);
ans=find(nums,target,0,m+1);
if(ans==-1)
ans=find(nums,target,m+1,nums.length);
return ans;
}
}