-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchInRotatedSortedArray.java
More file actions
72 lines (58 loc) · 1.62 KB
/
SearchInRotatedSortedArray.java
File metadata and controls
72 lines (58 loc) · 1.62 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package Leetcode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.PriorityQueue;
public class SearchInRotatedSortedArray
{
public static void main( String[] args )
{
SearchInRotatedSortedArray obj = new SearchInRotatedSortedArray();
System.out.println( obj.search( new int[] {3,1}, 1 ) );
}
public int search(int[] nums, int target) {
if(nums==null || nums.length==0)
return -1;
int pivotIndex = findPivotIndex(nums);
int l=0;
int h=nums.length-1;
if(pivotIndex==0 || pivotIndex==nums.length-1)
return search(nums, l, h, target);
else if(target<nums[0])
return search(nums, pivotIndex+1 , h, target);
else
return search(nums, 0, pivotIndex, target);
}
private int search(int[] nums, int l, int h, int target)
{
while(l<=h)
{
int mid = l+(h-l)/2;
if(nums[mid]==target)
return mid;
if(nums[mid]<target)
l = mid+1;
else
h = mid-1;
}
return -1;
}
private int findPivotIndex(int[] nums)
{
int l=0;
int r=nums.length-1;
int m=0;
while(l<=r)
{
m = l+(r-l)/2;
if(nums[m]>nums[l] && nums[m]>nums[r])
{
break;
}
else if(nums[m]>=nums[l])
l=m+1;
else
r=m-1;
}
return m;
}
}