forked from cpselvis/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution034.cpp
More file actions
62 lines (56 loc) · 927 Bytes
/
solution034.cpp
File metadata and controls
62 lines (56 loc) · 927 Bytes
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
/**
* Search for a Range
*
* cpselvis([email protected])
* September 11th, 2016
*/
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1;
vector<int> ret(2, -1);
while (nums[l] < nums[r])
{
int m = (l + r) / 2;
if (nums[m] < target)
{
l = m + 1;
}
else if (nums[m] > target)
{
r = m - 1;
}
else
{
if (nums[l] == target)
{
r --;
}
else
{
l ++;
}
}
}
if (nums[l] == target || nums[r] == target)
{
ret[0] = l;
ret[1] = r;
}
return ret;
}
};
int main(int argc, char **argv)
{
int arr[2] = {1, 4};
vector<int> vec(arr + 0, arr + 2);
Solution s;
vector<int> ret = s.searchRange(vec, 4);
for (auto i : ret)
{
cout << i << endl;
}
}