LeetCode:Search for a Range

Search for a Range

  My Submissions
Question Editorial Solution
Total Accepted: 86572  Total Submissions: 294138  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

Hide Tags
  Binary Search Array
Hide Similar Problems
  (E) First Bad Version






















思路:

两遍二分查找分别找出左右边界。


c++ code:

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        
        vector<int> ret(2,-1);
        int i=0,j=nums.size()-1;
        while(i < j) { // 找左边界
            int mid = (i+j)/2;
            if(nums[mid] < target)
                i = mid + 1;
            else
                j = mid;
        }
        if(target!=nums[i]) return ret;
        else ret[0] = i;
        
        j = nums.size()-1; // 这里i不需要置0
        while(i < j) { // 找右边界
            int mid = (i + j)/2 + 1;
            if(target < nums[mid])
                j = mid - 1;
            else
                i = mid;
        }
        ret[1] = i;
        return ret;
    }
};


你可能感兴趣的:(LeetCode,array,search,binary)