码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Search for a Range

时间:2017-12-05 13:30:06      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:lex   lower   end   else   int   for   search   val   div   

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) {
        if (nums.empty())
            return {-1, -1};
        int lower = -1, upper = -1, mid = 0;
        
        int left = 0, right = nums.size() - 1;
        while (left <= right) {
            mid = (left + right) / 2;
            if (nums[mid] < target)
                left = mid + 1;
            else
                right = mid - 1;
        }
        lower = left;
        
        left = 0, right = nums.size() - 1;
        while (left <= right) {
            mid = (left + right) / 2;
            if (nums[mid] > target) 
                right = mid - 1;
            else
                left = mid + 1;
        }
        upper = right;
        
        if (lower > upper)
            return {-1, -1};
        else 
            return {lower, upper};
    }
};
// 16 ms

 

[LeetCode] Search for a Range

标签:lex   lower   end   else   int   for   search   val   div   

原文地址:http://www.cnblogs.com/immjc/p/7986213.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!