Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n) .
If the target is not found in the array, return [-1, -1] .
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]Constraints:
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9nums is a non decreasing array.-10^9 <= target <= 10^9题意:在排序数组中确定数字 target 出现的左右边界。
用STL的二分查找函数。代码如下:
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int left = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); int right = upper_bound(nums.begin(), nums.end(), target) - nums.begin() - 1; if (left > right) return {-1, -1}; return vector<int>{left, right}; } };运行效率如下:
执行用时:20 ms, 在所有 C++ 提交中击败了74.62% 的用户 内存消耗:13.5 MB, 在所有 C++ 提交中击败了67.57% 的用户