-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path34.find-first-and-last-position-of-element-in-sorted-array.cpp
70 lines (64 loc) · 1.89 KB
/
34.find-first-and-last-position-of-element-in-sorted-array.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
// Tag: Array, Binary Search
// Time: O(logN)
// Space: O(1)
// Ref: -
// Note: std::lower_bound;
// Video: https://youtu.be/y6OT8heV-30
// Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
// If target is not found in the array, return [-1, -1].
// You must write an algorithm with O(log n) runtime complexity.
//
// Example 1:
// Input: nums = [5,7,7,8,8,10], target = 8
// Output: [3,4]
// Example 2:
// Input: nums = [5,7,7,8,8,10], target = 6
// Output: [-1,-1]
// Example 3:
// Input: nums = [], target = 0
// Output: [-1,-1]
//
//
// Constraints:
//
// 0 <= nums.length <= 105
// -109 <= nums[i] <= 109
// nums is a non-decreasing array.
// -109 <= target <= 109
//
//
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int first = lower_bound(nums, target);
if (first == nums.size() || nums[first] != target) {
return vector<int>{-1, -1};
}
int last = lower_bound(nums, target + 1) - 1;
return vector<int>{first, last};
}
int lower_bound(vector<int>& nums, int target) {
int start = 0;
int end = nums.size();
while (start < end) {
int mid = start + (end - start) / 2;
if (nums[mid] < target) {
start = mid + 1;
} else {
end = mid;
}
}
return start;
}
};
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
auto first = lower_bound(nums.begin(), nums.end(), target);
if (first == nums.end() || *first != target) {
return vector<int>{-1, -1};
}
auto last = lower_bound(nums.begin(), nums.end(), target + 1);
return vector<int>{int(first - nums.begin()), int(last - nums.begin() - 1)};
}
};