-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathsolve.cpp
More file actions
73 lines (73 loc) · 1.75 KB
/
Copy pathsolve.cpp
File metadata and controls
73 lines (73 loc) · 1.75 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
73
#include <vector>
#include <algorithm>
#include <iostream>
#include <cstdio>
using namespace std;
class Solution {
public:
vector<int> searchRange(int a[], int n, int target) {
vector<int> result(2, -1);
if (a == nullptr || n == 0)
return result;
int left = 0, right = n - 1;
bool found = false;
int mid = 0;
while (left <= right) {
mid = left + ((right - left) >> 1);
if (a[mid] == target) {
found = true;
break;
} else if (a[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
if (found) {
result[0] = leftSearch(a, left, mid, target);
result [1] = rightSearch(a, mid, right, target);
}
return result;
}
private:
int leftSearch(int a[], int start, int end, int target) {
int left = start, right = end;
while (left < right && a[right - 1] == target) {
if (a[left] == target)
return left;
int mid = left + ((right - left) >> 1);
if (a[mid] == target)
right = mid;
else
left = mid + 1;
}
return right;
}
int rightSearch(int a[], int start, int end, int target) {
int left = start, right = end;
while (left < right && a[left + 1] == target) {
if (a[right] == target)
return right;
int mid = left + ((right - left) >> 1);
if (a[mid] == target) {
left = mid;
}
else {
right = mid - 1;
}
}
return left;
}
};
int main(int argc, char **argv)
{
int a[100], n, key;
Solution solution;
while (scanf("%d%d", &n, &key) != EOF) {
for (int i = 0; i < n; ++i)
scanf("%d", a + i);
auto result = solution.searchRange(a, n, key);
printf("[%d, %d]\n", result[0], result[1]);
}
return 0;
}