# 【Leet Code】34. Search for a Ranged---Medium

Given a sorted array of integers, 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].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,

return [3, 4].

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if(nums.size() < 1) return {-1, -1};
int index1 = low_boundary(nums, target);
int index2 = low_boundary(nums, target+1) -1;

if(index1 < nums.size() && nums[index1] == target) return {index1, index2};
return {-1,-1};
}

private:
int low_boundary(vector<int>& nums, int target){

int left = 0, right = nums.size() - 1;
int mid = (left + right) / 2;
while(left <= right)
{
mid = (left + right) / 2;
if(target > nums[mid])
left = mid + 1;
else right = mid - 1;
}

return left;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：【Leet Code】34. Search for a Ranged---Medium 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)