Search for a Range

来源:互联网 发布:java主流工作流引擎 编辑:程序博客网 时间:2024/06/11 03:09

题目名称
Search for a Range—这里写链接内容

描述
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].

分析
  还是用到二分搜索,只是对结果进行简单的处理就行了。

C++代码

class Solution {public:    vector<int> searchRange(vector<int>& nums, int target) {        vector<int> res(2,-1);        int size = nums.size();        if(size==0 || target<nums[0] ||target>nums[size-1])            return res;        int l=0,r=size-1,mid;        while(l<=r) {            mid=(l+r)>>1;            if(nums[mid] == target) {                //找到target之后,需要两个位置值,分别向前向后遍历                int a=mid,b=mid;                while(a-1>=0 && nums[a-1]==target)                    a--;                while(b+1<size && nums[b+1]==target)                    b++;                res[0] = a;                res[1] = b;                return res;            }            else if(nums[mid] < target)                l=mid+1;            else                r=mid-1;        }        return res;    }};

总结
  

0 0