第一种方法,比较简单,左边界查找使用C++的upper_bound()
函数,右边界从左边界开始往下查找。
参考代码:
class Solution {
public:vector<int> searchRange(vector<int>& nums, int target) {vector<int> res;int len = nums.size();int left = lower_bound(nums.begin(), nums.end(), target) - nums.begin();if(left != len && nums[left] == target){res.push_back(left);}else {res.push_back(-1);res.push_back(-1);return res;}int right = left+1;while(right < len){if(nums[right] != target){break;}right++;}res.push_back(right-1);return res;}
};