12 ms C++ binary search


  • 0
    L
    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) { 
            int i = 0 , j = nums.size() - 1, k = -1, k1 = -1, k2 = -1 ; 
            while(i <= j){
                /*binary search*/
                int m = (i + j)/ 2;
                if(nums[m] == target){
                    k = m;
                    break;
                }else if(nums[m] < target){
                    i = m + 1;
                }else if(nums[m] > target){
                    j = m - 1;
                }
            }
            if(k == -1){return vector<int>({-1,-1});}
            i = 0, j = k,k1=k,k2=k;
            while(i <= j){
                int m = (i + j)/ 2;
                if(nums[m] == target){
                    k1 = m;
                    j = m  - 1;
                }else if(nums[m] < target){
                    i = m + 1;
                }
            }
            i = k, j = nums.size() - 1;
            while(i <= j){
                int m = (i + j)/2;
                if(nums[m] == target){
                    k2 = m;
                    i = m + 1;
                }else if(nums[m] > target){
                    j = m - 1;
                }
            }
            
            return vector<int>({k1, k2});
    
        }
    };

Log in to reply
 

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