算法描述:
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 = [,target = 8 Output: [3,4]5,7,8,10]
Example 2:
Input: nums = [,target = 6 Output: [-1,-1]5,10]
解题思路:
搜索问题,运行时间限制为O(log n) 首先考虑采用二分法。找到目标值之后向两边扩展,从而获得最终的结果。
vector<int> searchRange(vector<int>& nums,int target) { vector<int> results; int left = 0; int right = nums.size()-1; int leftIndex = -1; int rightIndex = -1; while(left <= right){ int middle = left + (right - left) / 2; if(nums[middle] > target) right = middle -1; else if(nums[middle] < target) left = middle+1; else{ leftIndex = middle; rightIndex = middle; while(leftIndex-1 >=0 && nums[leftIndex-1]==target) leftIndex--; while(rightIndex+1 <=nums.size()-1 && nums[rightIndex+1]==target) rightIndex++; break; } } results.push_back(leftIndex); results.push_back(rightIndex); return results; }