/*
* @lc app=leetcode id=34 lang=cpp
*
* [34] Find First and Last Position of Element in Sorted Array
*/
// @lc code=start
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if (nums.size() == 0) return vector<int>{-1, -1};
const auto lower_bound = [&](int target) {
int start = 0, end = nums.size() - 1;
while (start < end) {
int mid = start + (end - start) / 2;
if (nums[mid] < target) start = mid + 1;
else end = mid;
}
return start;
};
int l = lower_bound(target);
if (nums[l] != target) return vector<int>{-1, -1};
int h = lower_bound(target + 1);
if (nums[h] == target) return vector<int>{l, h};
return vector<int>{l, h - 1};
}
};
// @lc code=end
class Solution {
private int binSearch(int[] nums, int target) {
int start = 0, end = nums.length;
while (start < end) {
int mid = start + (end - start) / 2;
if (nums[mid] < target) {
start = mid + 1;
} else {
end = mid;
}
}
return start;
}
// find the first number that is greater than or equal to target.
// could return A.length if target is greater than A[A.length-1].
// actually this is the same as lower_bound in C++ STL.
public int[] searchRange(int[] nums, int target) {
int[] res = new int[]{-1, -1};
int start = binSearch(nums, target);
if (nums.length == start || nums[start] != target) {
return res;
}
res[0] = start;
res[1] = binSearch(nums, target + 1) - 1;
return res;
}
}