forked from gongluck/CVIP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
34.在排序数组中查找元素的第一个和最后一个位置.cpp
65 lines (62 loc) · 1.56 KB
/
34.在排序数组中查找元素的第一个和最后一个位置.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
/*
* @lc app=leetcode.cn id=34 lang=cpp
*
* [34] 在排序数组中查找元素的第一个和最后一个位置
*/
// @lc code=start
class Solution
{
public:
vector<int> searchRange(vector<int> &nums, int target)
{
int left = 0;
int right = nums.size() - 1;
int rightborder = -2;
while (left <= right)
{
int mid = left + ((right - left) >> 1);
int cur = nums[mid];
if (cur > target)
{
right = mid - 1;
continue;
}
else if (cur <= target)
{
left = mid + 1;
rightborder = left;
continue;
}
}
std::cout << "rightborder:" << rightborder << std::endl;
left = 0;
right = nums.size() - 1;
int leftborder = -2;
while (left <= right)
{
int mid = left + ((right - left) >> 1);
int cur = nums[mid];
if (cur < target)
{
left = mid + 1;
continue;
}
else if (cur >= target)
{
right = mid - 1;
leftborder = right;
continue;
}
}
std::cout << "leftborder:" << leftborder << std::endl;
if (leftborder == -2 || rightborder == -2 || leftborder + 1 >= rightborder)
{
return {-1, -1};
}
else
{
return {leftborder + 1, rightborder - 1};
}
}
};
// @lc code=end