LeetCode 34. Search for a Range

来源:互联网 发布:java如何实现线程 编辑:程序博客网 时间:2024/06/06 03:28

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

class Solution {public:    vector<int> searchRange(vector<int>& nums, int target) {        vector<int> v(2);        int l=0,r=nums.size()-1,m=0;        while(l<=r){            m=l+(r-l)/2;            if(nums[m]>target) r=m-1;            else if(nums[m]<target) l=m+1;            else break;        }        if(l>r){            v[0]=-1;v[1]=-1;return v;        }        while(nums[l]!=target) l++;        while(nums[r]!=target) r--;        v[0]=l;v[1]=r;        return v;    }};

原创粉丝点击