Python - Simple binary search - O(logn) , beats 95%


  • 0
    A
    class Solution(object):
        def searchInsert(self, nums, target):
            left = 0
            right = len(nums) - 1
            
            while left < right:
                mid = (left + right) // 2
                if nums[mid] == target:
                    return mid
                elif nums[mid] < target:
                    left = mid + 1
                else:
                    right = mid - 1
                    
            return left + 1 if nums[left] < target else left
    

Log in to reply
 

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