LeetCode第34题之Search for a Range

C++代码:

#include 
#include 
using namespace std;

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> res(2, -1);
        int sz = nums.size();
        int l = 0;
        int r = sz-1;
        int mid;
        while (l<=r)
        {
            mid = (l+r)/2;
            if (nums[mid]>= target)
            {
                r = mid-1;
            }
            else
            {
                l = mid+1;
            }
        }//此时r必是比target小的第一个数的下标
        res[0] = r+1;

        l = 0;
        r = sz-1;
        while (l<=r)
        {
            mid = (l+r)/2;
            if (nums[mid] <= target)
            {
                l = mid+1;
            }
            else
            {
                r = mid-1;
            }
        }//此时l必是比target大的第一个数的下标
        res[1] = l-1;

        //如果不存在这样的数
        if (res[0] > res[1])
        {
            res[0] = -1;
            res[1] = -1;
        }
        return res;
    }
}; 


int main()
{
    Solution s;
    vector<int> v;
    v.push_back(5);
    v.push_back(7);
    v.push_back(7);
    v.push_back(8);
    v.push_back(8);
    v.push_back(10);
    vector<int> res = s.searchRange(v,10);
    for (int i=0;icout<'\t';
    }
    cout<return 0;
}

你可能感兴趣的:(LeetCode算法,leetcode)