Search for a Range
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Search for a Range相关的知识,希望对你有一定的参考价值。
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) { int mid,start=0,end=nums.size()-1; vector<int> res; while(start<=end){ mid=start+(end-start)/2; if(nums[mid]>target) end=mid-1; else if(nums[mid]<target) start=mid+1; else{ int left=mid,right=mid; while(left>=0&&nums[left]==target) left--; left=left+1; while(right<nums.size()&&nums[right]==target) right++; right=right-1; res.push_back(left); res.push_back(right); break; } } if(res.empty()){ res.push_back(-1); res.push_back(-1); } return res; } };
以上是关于Search for a Range的主要内容,如果未能解决你的问题,请参考以下文章