Solution with only one return


  • 0
    L
    function searchInsert(nums, target) {
        var l = 0;
        var r = nums.length - 1;
        
        while (l <= r) {
            var mid = (l + r) >> 1;
            
            if (nums[mid] >= target) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        
        // nums[r] is the largest number which nums[r] < target if exists
        // nums[l] is the smallest number which nums[l] >= target if exists
        return l;
    }

Log in to reply
 

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