forked from Tanisha800/leetcode_solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
firstLastOcc.cpp
75 lines (66 loc) · 1.93 KB
/
firstLastOcc.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
66
67
68
69
70
71
72
73
74
/*
Problem: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description
*/
#include <iostream>
#include <vector>
using namespace std;
int firstPosition(vector<int>& nums, int &target){
int n = nums.size();
int start = 0, end = n - 1;
int ans = -1;
while(start <= end){
int mid = start + (end - start) / 2;
if(nums[mid] == target){
ans = mid;
//this can be the possible firstIdx
//but we are not sure so keep on searching
//towards left of mid
end = mid - 1;
}else if(target > nums[mid]){
start = mid + 1;
}else{
end = mid - 1;
}
}
return ans;
}
int lastPosition(vector<int>& nums, int &target){
int n = nums.size();
int start = 0, end = n - 1;
int ans = -1;
while(start <= end){
int mid = start + (end - start) / 2;
if(nums[mid] == target){
//this can be the possible last Index
//but we are not sure so keep on searching
//towards right of mid
ans = mid;
start = mid + 1;
}else if(target > nums[mid]){
start = mid + 1;
}else{
end = mid - 1;
}
}
return ans;
}
vector<int> searchRange(vector<int>& nums, int target) {
int first = firstPosition(nums, target);
if(first == -1){
return {-1, -1};
}
int last = lastPosition(nums, target);
return {first, last};
}
int main(){
int n, target;
cin >> n >> target;
vector<int> nums(n);
for(int i = 0; i < n; ++i){
cin >> nums[i];
}
vector<int> output = searchRange(nums, target);
for(int i = 0; i < output.size(); ++i){
cout << output[i] << " ";
}
}