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

【LeetCode】Search for a Range

时间:2014-12-18 00:04:06      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   io   color   os   sp   for   

Search for a Range

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

 

由于O(logn)时间要求,显然用二分查找。

思路是先用二分查找找到其中一个target,找不到则返回[-1, -1]

找到之后从这个位置往两边递归进行二分查找进行范围的拓展。

部分参考了xiao.he.587的思路。

class Solution {
public:
    vector<int> searchRange(int A[], int n, int target) {
        vector<int> ret(2, -1);
        int ind = Helper(A, 0, n-1, target);
        if(ind != -1)
        {//find one target
            int left = ind;
            int right = ind;
            ret[0] = left;
            ret[1] = right;
            //recursively extend left towards 0
            while((left = Helper(A, 0, left-1, target)) != -1)
                ret[0] = left;
            //recursively extend right towards n-1
            while((right = Helper(A, right+1, n-1, target)) != -1)
                ret[1] = right;
        }
        return ret;
    }
    int Helper(int A[], int low, int high, int target)
    {//binary search
        while(low <= high)
        {
            int mid = low + (high-low)/2;
            if(A[mid] == target)
                return mid;
            else if(A[mid] > target)
                high = mid-1;
            else
                low = mid+1;
        }
        return -1;
    }
};

bubuko.com,布布扣

【LeetCode】Search for a Range

标签:style   blog   http   ar   io   color   os   sp   for   

原文地址:http://www.cnblogs.com/ganganloveu/p/4170659.html

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