C++ solution using two binary search


  • 0
    Z

    Can anybody please kindly explain why there are runtime errors

    class Solution {
    public:
    vector<int> searchRange(vector<int> &A, int target) {
    int start, end, mid;
    vector<int>range;

        //  find left bound;
        start = 0;
        end = A.size() - 1;
        while (start + 1 < end) {
            mid = start + (end - start) / 2;
            if (A[mid] == target) {
                end = mid;
            } else if (A[mid] < target) {
                start = mid;
            } else {
                end = mid;
            }
        }  // while loop
        if (A[start] == target) {
            range[0] = start;
        } else if (A[end] == target) {
            range[0] = end;
        } else {
            range[0] = range[1] = -1;
            return range;
        }
        
        // find the right bound
        start = 0;
        end = A.size() - 1;
        while (start + 1 < end) {
            mid = start + (end - start)/2;
            if (A[mid] == target) {
                start = mid;
            } else if (A[mid] < target) {
                start = mid;
            } else {
                end = mid;
            }
        }  // while loop
        if (A[end] == target) {
            range[1] = end;
        } else if (A[start] == target) {
            range[1] = start;
        } else {
            range[0] = range[1] = -1;
            return range;
        }
        return range;
    }
    

    };
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.