6 lines python O(logn) solution


  • 0
    C

    binary search

        def searchInsert(self, nums, target):
            i,j  = 0, len(nums) - 1
            while i <= j:
                if target <= nums[i]: return i
                if target >= nums[j]: return j + 1 if target > nums[j] else j
                i,j = i+1, j-1
            return len(nums)/2 # if target is in the middle
    

Log in to reply
 

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