现在的位置: 首页 > 综合 > 正文

Search for a Range

2019年07月25日 ⁄ 综合 ⁄ 共 979字 ⁄ 字号 评论关闭

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

思路:这道题是binary search的改进版。当寻找到target所在的k位置时,需要判断target的起始索引值和终止索引值。可以这么思考:首先得到k的位置,如果k不存在则返回[-1,-1];如果k存在,则起始的索引值肯定是在k的左半侧,终止索引值在k的右半侧。然后对这两侧再进行二分查找。因此总共的时间复杂度为O(n)。
class Solution {
public:
    vector<int> searchRange(int A[], int n, int target) {
        vector<int> res;
        res.clear();
        if (n<=0) {
            res.push_back(-1);
            res.push_back(-1);
            return res;
        }
        int L = 0, R = n - 1, M;
        while(L <= R) {
            M = (L + R) / 2;
            if (A[M] > target) {
                R = M - 1;
            }
            else if(A[M] < target) {
                L = M + 1;
            }
            else {
                break;
            }
        }
        if (A[M] != target) {
            res.push_back(-1);
            res.push_back(-1);
        }
        else {
            L = 0, R = M - 1;
            int mid;
            while(R>=0 && A[R]==target) {
                mid = (L + R) / 2;
                if (A[mid] < target) {
                    L = mid + 1;
                }
                else if(A[mid] >= target) {
                    R = mid - 1;
                }
            }
            res.push_back(R + 1);
            L = M + 1,R = n - 1;
            while(L<n && A[L] == target) {
                mid = (L + R) / 2;
                if (A[mid] <= target) {
                    L = mid + 1;
                }
                else {
                    R = mid - 1;
                }
            }
            res.push_back(L-1);
        }
        return res;
    }
};
【上篇】
【下篇】

抱歉!评论已关闭.