-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0033-search-in-rotated-sorted-array.c
62 lines (47 loc) · 1.34 KB
/
0033-search-in-rotated-sorted-array.c
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
int findPivotIndex(int* nums, int numsSize)
{
int s = 0;
int e = numsSize;
while(s <= e){
int m = s + (e - s)/2;
if(m < e && nums[m] > nums[m+1]){
return m;
}
else if(s < m && nums[m] < nums[m-1]){
return m - 1;
}
else if(nums[s] < nums[m]){
s = m + 1;
}
else if(nums[s] >= nums[m]){
e = m - 1;
}
}
// If the array is not rotated then last position will be the pivot element.
return numsSize;
}
int binarySearch(int *nums, int s, int e, int target)
{
while(s <= e){
int m = s + (e - s)/2;
if(nums[m] == target){
return m;
}
else if(nums[m] < target){
s = m + 1;
}
else{
e = m - 1;
}
}
return -1;
}
int search(int* nums, int numsSize, int target){
int n = numsSize - 1;
int pivotIndex = findPivotIndex(nums, n);
int firstTry = binarySearch(nums, 0, pivotIndex, target);
if(firstTry != -1){
return firstTry;
}
return binarySearch(nums, pivotIndex + 1, n, target);
}