My intuitive two pass binary search solution


  • 0
    R
    class Solution {
    public:
        vector<int> searchRange(int A[], int n, int target) {
            int start = -1;
            int end = n;
            while(end-start > 1){
                int mid = (end-start)/2 + start;
                if(A[mid] >= target){
                    end = mid;
                }
                else{
                    start = mid;
                }
            }
            if(A[start+1] != target)
                start = -2;
                
            int final_start = start+1;
             
             start = -1;
             end = n;
            while(end-start > 1){
                int mid = (end-start)/2 + start;
                if(A[mid] > target){
                    end = mid;
                }
                else{
                    start = mid;
                }
            }
            if(A[end-1]!=target)
                end = 0;
            int final_end = end-1;
            vector<int> res;
            res.push_back(final_start);
            res.push_back(final_end);
            return res;
        }
    };
    

    I use two passes to find the starting point and ending point respectively.


Log in to reply
 

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