-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_STO_0053_search.cc
84 lines (76 loc) · 1.36 KB
/
Problem_STO_0053_search.cc
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
79
80
81
82
83
84
#include <iostream>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
int nearLeft(vector<int> &arr, int target)
{
int left = 0;
int right = arr.size() - 1;
int index = -1;
while (left <= right)
{
int mid = (right - left) / 2 + left;
if (target <= arr[mid])
{
index = mid;
right = mid - 1;
}
else
{
left = mid + 1;
}
}
return index;
}
int nearRight(vector<int> &arr, int target)
{
int left = 0;
int right = arr.size() - 1;
int index = -1;
if (arr[right] < target)
{
return -1;
}
while (left <= right)
{
int mid = (right - left) / 2 + left;
if (arr[mid] <= target)
{
index = mid;
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return index;
}
int search(vector<int> &nums, int target)
{
if (nums.size() == 0)
{
return 0;
}
int left = nearLeft(nums, target);
int right = nearRight(nums, target);
return left != -1 && right != -1 ? right - left + 1 : 0;
}
};
void test()
{
Solution s;
vector<int> n1 = {5, 7, 7, 8, 8, 10};
EXPECT_EQ_INT(1, s.search(n1, 5));
EXPECT_EQ_INT(2, s.search(n1, 8));
EXPECT_EQ_INT(0, s.search(n1, 11));
EXPECT_SUMMARY;
}
int main()
{
test();
return 0;
}