34. Search for a Range
题目
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].
解析
- 关于二分法的查找延伸的问题,细节要注意
- 注意使用stl的函数实现,在[first,last)区间查找
class Solution_34 {public: int findUpBound(vector & nums, int target) //找上边界 { int low = 0, high = nums.size() - 1; if (nums.back() > 1; if (nums[mid]<=target) /// 向右夹逼,找到右边界 { low = mid + 1; } else { high = mid - 1; } } return high; //向右夹逼,返回high } int findDownBound(vector & nums, int target) // 找下边界 { int low = 0, high = nums.size() - 1; if (nums.front()>target) { return -1; } while (low<=high) { int mid = (low + high) >> 1; if (nums[mid]
vec(2, -1); if (nums.size() == 0 || nums.front()>target || nums.back()