-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path34_first_last_position_sorted.cpp
50 lines (44 loc) · 1.03 KB
/
34_first_last_position_sorted.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
// LC 34
/*Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]*/
//TC = O(logn) SC =O(n);
#include <bits/stdc++.h>
using namespace std;
vector<int>searchRange(vector<int>&nums, int target) {
//store ans
vector<int> ans = {-1,-1};
//binary search
int s = 0;
int e = nums.size() -1 ;
while(s<=e) {
int mid = s + (e-s)/2;
if(nums[mid] == target) {
//make sure the array index out of bound error does not occur
while(mid > 0 && nums[mid-1] == target) {
mid--;
}
ans[0] = mid;
while(mid < nums.size() - 1 && nums[mid+1] == target) {
mid++;
}
ans[1]= mid;
return ans;
}
else if(nums[mid] > target) {
e = mid - 1;
}
else {
s = mid + 1;
}
}
return ans;
}
int main() {
vector<int> arr = {5,7,7,8,8,10};
vector<int> ans = searchRange(arr, 8);
for(auto itr: ans) {
cout << itr <<" ";
}
return 0;
}