-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirst_And_Last_Element.cpp
More file actions
48 lines (45 loc) · 1.38 KB
/
First_And_Last_Element.cpp
File metadata and controls
48 lines (45 loc) · 1.38 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
#include "string"
#include "map"
#include "stack"
#include "vector"
#include "iostream"
using namespace std;
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> answer = {-1, -1};
if (nums.size() < 1) {
return answer;
} else if (nums.size() == 1 && target == nums[0]) {
answer = {0,0};
return answer;
}
int position = binarySearch(nums, 0, nums.size()-1, target);
if (position != -1) {
int position2 = position+1;
while (position2 < nums.size() && nums[position2] == target) {
position2++;
}
position2--;
answer = {position, position2};
}
return answer;
}
int binarySearch(vector<int>& nums, int begin, int end, int target) {
if (begin > end) {
return -1;
}
int medianIndex = (begin + end)/ 2;
if (target == nums[medianIndex]) {
medianIndex--;
while (medianIndex >= 0 && nums[medianIndex] == target) {
medianIndex--;
}
return medianIndex+1;
} else if (target > nums[medianIndex]) {
return binarySearch(nums, medianIndex + 1, end, target);
} else {
return binarySearch(nums, begin, medianIndex - 1, target);
}
}
};