-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_0034_searchRange.cc
86 lines (79 loc) · 1.42 KB
/
Problem_0034_searchRange.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
85
86
#include <iostream>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
int findFirst(vector<int> &nums, int target)
{
int l = 0;
int r = nums.size() - 1;
int index = -1;
while (l <= r)
{
int m = (r - l) / 2 + l;
if (target <= nums[m])
{
if(target == nums[m])
{
index = m;
}
r = m - 1;
}
else
{
l = m + 1;
}
}
return index;
}
int findLast(vector<int> &nums, int target)
{
int l = 0;
int r = nums.size() - 1;
int index = -1;
while (l <= r)
{
int m = (r - l) / 2 + l;
if (nums[m] <= target)
{
if(nums[m] == target)
{
index = m;
}
l = m + 1;
}
else
{
r = m - 1;
}
}
return index;
}
vector<int> searchRange(vector<int> &nums, int target)
{
int a = findFirst(nums, target);
int b = findLast(nums, target);
return {a, b};
}
};
bool isVectorEqual(vector<int> a, vector<int> b)
{
return a == b;
}
void testSearchRange()
{
Solution s;
vector<int> n1 = {5, 7, 7, 8, 8, 10};
vector<int> n2 = {};
EXPECT_TRUE(isVectorEqual({3, 4}, s.searchRange(n1, 8)));
EXPECT_TRUE(isVectorEqual({-1, -1}, s.searchRange(n1, 6)));
EXPECT_TRUE(isVectorEqual({-1, -1}, s.searchRange(n2, 0)));
EXPECT_SUMMARY;
}
int main()
{
testSearchRange();
return 0;
}