-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSearchRotatedArray.cpp
68 lines (58 loc) · 1.56 KB
/
SearchRotatedArray.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Leetcode https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/804/
#include <iostream>
#include <vector>
void print(const std::vector<int>& nums)
{
for (auto n : nums) {
std::cout << n << " ";
}
}
int search(const std::vector<int>& nums, const int target)
{
if (nums.empty()) {
return -1;
}
int left = 0;
int right = nums.size() - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
} else {
if (nums[left] <= nums[mid]) {
if (nums[left] <= target && target <= nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
if (nums[mid] <= target && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
}
return nums[left] == target ? left : -1;
}
void test(const std::vector<int>& nums, const int target)
{
std::cout << "Numbers : ";
print(nums);
std::cout << "\n";
std::cout << "Target : " << target << "\n";
std::cout << "Target found at index : " << search(nums, target);
std::cout << "\n======================================\n";
}
int main()
{
std::vector<int> nums {4,5,6,7,0,1,2};
int target = 0;
test(nums, target);
target = 3;
test(nums, target);
target = 7;
test(nums, target);
return 0;
}