simple python solution


  • 0
    N

    use binary search, find the first number that biger or equal to the target

    class Solution(object):
        def searchInsert(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            if not nums:
                return 0
            if target > nums[len(nums) - 1]:
                return len(nums)
            
            left = 0
            right = len(nums) - 1
            while left < right:
                mid = left + (right - left)/2
                if nums[mid] < target:
                    left = mid + 1
                else:
                    right = mid
            
            return left
    

Log in to reply
 

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