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

[LeetCode] Search for a Range 搜索一个范围

时间:2015-04-09 13:33:59      阅读:123      评论: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].

 

这道题让我们在一个有序整数数组中寻找相同目标值的起始和结束位置,而且限定了时间复杂度为O(logn),这是典型的二分查找法的时间复杂度,所以这道题我们也需要用此方法,我们的思路是首先对原数组使用二分查找法,找出其中一个目标值的位置,然后向两边搜索找出起始和结束的位置,代码如下:

 

class Solution {
public:
    vector<int> searchRange(int A[], int n, int target) {
        vector<int> res;
        int idx = searchRangeDFS(A, 0, n - 1, target);
        if (idx == -1) res.resize(2, -1);
        else {
            int left = idx;
            while (left > 0 && A[left - 1] == A[idx]) --left;
            int right = idx;
            while (right < n - 1 && A[right + 1] == A[idx]) ++right;
            res.push_back(left);
            res.push_back(right);
        }
        return res;
    }
    int searchRangeDFS(int A[], int left, int right, int target) {
        if (left > right) return -1;
        int mid = (left + right) / 2;
        if (A[mid] == target) return mid;
        if (A[mid] < target) return searchRangeDFS(A, mid + 1, right, target);
        else return searchRangeDFS(A, left, mid - 1, target);
    }
};

 

http://fisherlei.blogspot.com/2013/01/leetcode-search-for-range.html

 

[LeetCode] Search for a Range 搜索一个范围

标签:

原文地址:http://www.cnblogs.com/grandyang/p/4409379.html

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