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

126人阅读 评论(0)

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;
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：6803次
• 积分：371
• 等级：
• 排名：千里之外
• 原创：31篇
• 转载：3篇
• 译文：0篇
• 评论：0条
阅读排行