LeetCode——Search for a Range

1. Question

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

2. Solution

二分查找,找最左边和目标相等的数,找右边和密保相等的数。 时间复杂度O(lgn)。

3. Code

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        
        int start = 0;
        int end = nums.size() - 1;
        vector<int> res(2, -1);
        // 数组为空,注意判断
        if (nums.size() == 0)
            return res;
        // 找最左边和目标值相等
        while (start < end) {
            int mid = (start + end) >> 1;
            if (nums[mid] < target) start = mid + 1;
            else end = mid;
        }
        if (nums[start] == target)
            res[0] = start;
        else
            return res;
        
        end = nums.size() - 1;
        while (start < end) {
            int mid = ((start + end) >> 1) + 1;   // 使中间值偏向右边
            if (nums[mid] > target) end = mid - 1;
            else start = mid;
        }
        res[1] = end;
        return res;
    }
    
};
posted @ 2017-11-11 21:48  清水汪汪  阅读(115)  评论(0编辑  收藏  举报