# LeetCode-34. Search for a Range

## Description

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]

## Solution 1(C++)

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> res;
int midl, leftl=0, rightl=nums.size()-1;
int midr, leftr=0, rightr=nums.size()-1;
while(leftl<rightl || leftr<rightr){
midl = leftl + ((rightl-leftl)>>1);
midr = leftr + ((rightr-leftr+1)>>1);
if(nums[midl] < target) leftl = midl+1;
else rightl = midl;
if(nums[midr] > target) rightr = midr-1;
else leftr = midr;
}
if(rightl < nums.size() && nums[rightl]==target) res.push_back(rightl);
else res.push_back(-1);
if(leftr < nums.size() && nums[leftr]==target) res.push_back(leftr);
else res.push_back(-1);
return res;
}
};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120