-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day-10-search-in-rotated-sorted-array.cpp
48 lines (46 loc) · 1.27 KB
/
Day-10-search-in-rotated-sorted-array.cpp
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
class Solution
{
public:
int search(vector<int> &nums, int target)
{
int n = nums.size();
int low = 0, high = n - 1;
while (low <= high)
{
int mid = low + (high - low) / 2;
// check if it exists
if (nums[mid] == target)
return mid;
// otherwise check for sorted half --> since no duplicates, no edge cases
// left half sorted
if (nums[low] <= nums[mid])
{
if (nums[low] <= target && target <= nums[mid])
{
// present in sorted half
high = mid - 1;
}
else
{
// not present int sorted half
low = mid + 1;
}
}
// right half sorted
if (nums[mid] <= nums[high])
{
if (nums[mid] <= target && target <= nums[high])
{
// present in sorted half
low = mid + 1;
}
else
{
// not present int sorted half
high = mid - 1;
}
}
}
return -1;
}
};