Elegant Java Binary Search Solution


  • 0
    K
     public int searchInsert(int[] nums, int target) {
            int lo=0;
            int hi= nums.length -1;
            int mid=-1;
    
            while( lo <= hi){
                mid= lo + ( hi - lo )/2;
                if( target < nums[mid])
                    hi= mid -  1;
                else if( target > nums[mid])
                    lo = mid + 1;
                else
                    return mid;
            }
    
            return  mid + (( target > nums[mid])? 1 : 0);
        }

Log in to reply
 

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