Skip to content

Latest commit

 

History

History
31 lines (24 loc) · 800 Bytes

35. Search Insert Position.md

File metadata and controls

31 lines (24 loc) · 800 Bytes

35. Search Insert Position (Easy)

  • range: 0 to len -1
  • target: index of the element if found, or the index of the greater element.
  • if there is no greater element, index = len
class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        left, right = 0, len(nums) - 1
        temp_index = None
        while(left <= right):
            mid = left + (right - left) // 2 
            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                temp_index = mid
                right = mid - 1
            else:
                left = mid + 1
        # or dont use the temp_index and just return left.
        if temp_index == None:
            temp_index = len(nums)
        
        return temp_index