[Leetcode]Search for a Range

Search for a Range My Submissions Question
Total Accepted: 64904 Total Submissions: 232560 Difficulty: Medium
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].

Subscribe to see which companies asked this question
一次找到第一个出现的位置,另一次找到最后一个出现的位置。进行替代即可

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> res{-1,-1};
        res[0] = findFirst(nums,target);
        res[1] = findLast(nums,target);
        return res;
    }

private:
    int findFirst(const vector<int>& nums,int target){
        int l = 0;
        int r = nums.size() - 1;
        int mid;
        while(l < r){
            mid = l + (r - l) / 2;
            if(nums[mid] < target){
                l = mid + 1;
            }
            else if(nums[mid] > target){
                r = mid;
            }
            else{
                if(l == mid)    return l;
                else r = mid;
            }
        }
        if(nums[l] == target) return l;
        else return -1;
    }
    int findLast(const vector<int>& nums,int target){
        int l = 0;
        int r = nums.size() - 1;
        int mid;
        while(l < r - 1){
            mid = l + (r - l) / 2;
            if(nums[mid] < target){
                l = mid + 1;
            }
            else if(nums[mid] > target){
                r = mid - 1;
            }
            else{
                l = mid;
            }
        }
        if(nums[r] == target)   return r;
        else if(nums[l] == target)   return l;
        else return -1;
    }
};

posted on 2015-11-25 21:47  泉山绿树  阅读(24)  评论(0)    收藏  举报

导航