My accepted binary search solution ( >= target )


  • 0
    V
    def searchInsert(self, nums, target):
            nums.append(2147483647)
            
            l, r = 0, len(nums) - 1
            
            while l < r:
                mid = l + (r - l) / 2
                
                if nums[mid] >= target:
                    r = mid
                else:
                    l = mid + 1
            
            return l
    

    This question is to find the first element >= target (Binary search - 3.1.2 Loose Upper bound(>=target)).
    But if target larger than the last element(i.e. [1,2,3,6,7] target = 9 return 5), the template code of loose upper bound will return len(nums) - 1, not len(nums). So, append Integer.MAX_VALUE to last.

    Learn more


Log in to reply
 

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