-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSearchRange.cpp
78 lines (67 loc) · 1.9 KB
/
SearchRange.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
69
70
71
72
73
74
75
76
77
78
// Leetcode https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/802/
#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, const bool firstIndex)
{
int left = 0;
int right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
if (firstIndex) {
if (mid == left || nums[mid - 1] != target) {
return mid;
}
right = mid - 1;
} else {
if (mid == right || nums[mid + 1] != target) {
return mid;
}
left = mid + 1;
}
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
std::vector<int> searchRange(const std::vector<int>& nums, int target)
{
if (nums.empty() || target < nums[0] || target > nums.back()) {
return {-1, -1};
}
int startIndex = search(nums, target, true);
if (startIndex == -1) {
return {-1,-1};
}
int endIndex = search(nums, target, false);
return {startIndex, endIndex};
}
void test(const std::vector<int>& nums, const int target)
{
std::cout << "Array : ";
print(nums);
std::cout << ", searching " << target << "\n";
std::vector<int> index = searchRange(nums, target);
std::cout << "Found at " << "[" << index[0] << ", " << index[1] << "]\n";
std::cout << "===============================================\n";
}
int main()
{
std::vector<int> nums {5,5,7,7,8,8,10,10,10};
test(nums, 5);
test(nums, 8);
test(nums, 10);
test(nums, 6);
test(nums, 12);
test(nums, 0);
return 0;
}