Given an array of integers 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].
For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4].
这题要在O(log n)的时间复杂度内找到这个范围,而这是一个有序的数组,那么可以用二分查找法进行查找。
AC:
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> res; int l=0; int r=nums.size()-1; while(l<=r) { if(nums[l]<target) l++; if(nums[r]>target) r--; if(nums[l]==target&&nums[r]==target) { res.push_back(l); res.push_back(r); return res; } } res.push_back(-1); res.push_back(-1); return res; } };