Search for a Range

Description

Given a sorted array of_n_integers, find the starting and ending position of a given target value.

If the target is not found in the array, return[-1, -1].

Example

Given [5, 7, 7, 8, 8, 10] and target value 8,

return [3, 4].

Challenge

O(log n) time.

Related problems

Total Occurrence of Target

Implementation

Link: http://lintcode.com/en/problem/search-for-a-range/

public:
    vector<int> searchRange(vector<int> &A, int target) {
        // write your code here
        vector<int> ret;
        vector<int> retWithErr(2, -1);

        if(A.size() == 0) {
            return retWithErr;
        }

        // Find the first pos
        int start = 0, end = A.size() - 1;
        while(start + 1 < end) {
            int mid = start + (end - start) / 2;
            if(A[mid] >= target) {
                end = mid;
            } else { // A[mid] < target
                start = mid;
            }
        }
        if(A[start] == target) {
            ret.push_back(start);
        } else if(A[end] == target) {
            ret.push_back(end);
        } else {
            return retWithErr;
        }

        // Find the last pos
        start = 0;
        end = A.size() - 1;
        while(start + 1 < end) {
            int mid = start + (end - start) / 2;
            if(A[mid] <= target) {
                start = mid;
            } else { // A[mid] < target
                end = mid;
            }
        }
        if(A[end] == target) {
            ret.push_back(end);
        } else if(A[start] == target) {
            ret.push_back(start);
        } else {
            return retWithErr;
        }

        return ret;
    }
};

results matching ""

    No results matching ""