LeetCode Search for a Range

来源:互联网 发布:sas编程 编辑:程序博客网 时间:2024/05/01 13:21

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 low(0), mid, high(nums.size()-1),findlast,maxlen=nums.size()-1;if (low == high){if (nums[low]==target){return vector<int>{0, 0};}}while (low<=high){mid = (low + high) / 2;if (nums[mid]<target){low = mid +1;}else{if (nums[mid]>target)high = mid - 1;else{findlast = mid;while (mid-1>=0 && nums[mid-1]==target){--mid;}while (findlast+1<=maxlen&&nums[findlast+1]==target){++findlast;}return vector<int>{mid, findlast};}}}return vector<int>{-1, -1};}};


0 0
原创粉丝点击