6 lines Python solution O(logn)

  • -1

    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```

  • 0

    Is this linear search? How this is O(logn) can you please explain?

Log in to reply

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