-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0034.cpp
More file actions
executable file
·44 lines (41 loc) · 972 Bytes
/
LC0034.cpp
File metadata and controls
executable file
·44 lines (41 loc) · 972 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
/*
Problem Statement: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
Time: O(log n)
Space: O(1)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
// use 2 binary searches
int beg, end;
beg = lower_bound(nums, target);
end = upper_bound(nums, target) - 1;
if (beg == nums.size() || nums[beg] != target)
return {-1, -1};
else
return {beg, end};
}
int lower_bound(vector<int>& nums, int target) {
int low = 0, high = nums.size();
while (low < high) {
int mid = low + (high - low) / 2;
if (nums[mid] < target)
low = mid + 1;
else
high = mid;
}
return low;
}
int upper_bound(vector<int>& nums, int target) {
int low = 0, high = nums.size();
while (low < high) {
int mid = low + (high - low) / 2;
if (nums[mid] > target)
high = mid;
else
low = mid + 1;
}
return high;
}
};