首页 > 编程语言 > 详细

leetcode:Search for a Range(数组,二分查找)

时间:2015-10-06 18:00:36      阅读:252      评论:0      收藏:0      [点我收藏+]

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

分析:题意为在一个有序数组中找到给定目标值的起始位置并返回,如果目标值不存在则返回[1,1].

思路:使用binarySearchLow()去找到不小于目标值数字的最小索引,使用binarySearchUp()去找到不大于目标值数字的最大索引,然后即可得到索引范围。

code如下:

class Solution {
private:
    int binarySearchLow(vector<int>& nums, int target, int begin, int end)
    {
        if(begin > end) return begin;
        int mid = begin + (end - begin) / 2;
        if(nums[mid] < target) return binarySearchLow(nums, target, mid + 1, end);
        else return binarySearchLow(nums, target, begin, mid - 1);
    }
    int binarySearchUp(vector<int>& nums, int target, int begin, int end)
    {
        if(begin > end) return end;
        int mid = begin + (end - begin) / 2;
        if(nums[mid] > target) return binarySearchUp(nums, target, begin, mid - 1);
        else return binarySearchUp(nums, target, mid + 1, end);
    }
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> res(2, -1);
        if(nums.empty()) return res;
        int high = binarySearchUp(nums, target, 0, nums.size() -1);
        int low = binarySearchLow(nums, target, 0, nums.size() - 1);
        if(high >= low)
        {
            res[0] = low;
            res[1] = high;
            return res;
        }
        return res;
    }
};

  

leetcode:Search for a Range(数组,二分查找)

原文:http://www.cnblogs.com/carsonzhu/p/4857327.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!