描述:
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 = 8Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6Output: [-1,-1]
思路一:一次Binary Search
先使用二分查找找到和taget相等的起始位置的元素,然后在这个位置向两边扩散找到值相同的范围。
class Solution {public: vector searchRange(vector & nums, int target) { vector res(2,-1); if(nums.size() == 0) return res; int cau = dichotomy(nums,target); if(cau == -1) return res; else{ int i = cau,j = cau; cout<< =0 && nums[i] == target) || (j<=nums.size()-1 && nums[j] == target)){ if(i>=0 && nums[i] == target){ res[0] = i; cout< <