赞
踩
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
进阶:你可以设计并实现时间复杂度为 $O(\log n)$ 的算法解决此问题吗?
示例 1:
示例 2:
示例 3:
- # C++
- class Solution {
- public:
- vector<int> searchRange(vector<int>& nums, int target) {
- int rightBorder = getRightBorder(nums, target);
- int leftBorder = getLeftBorder(nums, target);
- # 1
- if(leftBorder == -2 || rightBorder == -2){
- return {-1, -1};
- }
- # 2
- if(rightBorder - leftBorder > 1){
- return {leftBorder + 1, rightBorder - 1};
- }
- # 3
- return {-1, -1};
- }
-
- private:
- int getRightBorder(vector<int>& nums, int target){
- int left = 0;
- int right = nums.size() - 1;
- int rightBorder = -2;
- while(left <= right){
- int mid = (right - left) / 2 + left;
- if(nums[mid] > target){
- right = mid - 1;
- }else{
- left = mid + 1;
- rightBorder = left;
- }
- }
- return rightBorder;
- }
-
- int getLeftBorder(vector<int>& nums, int target){
- int left = 0;
- int right = nums.size() - 1;
- int leftBorder = -2;
- while(left <= right){
- int mid = (right - left) / 2 + left;
- if(nums[mid] >= target){
- right = mid - 1;
- leftBorder = right;
- }else{
- left = mid + 1;
- }
- }
- return leftBorder;
- }
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。