An overthought solution, could be optimized


  • 0
    B
    class Solution(object):
        def searchInsert(self, nums, target):
            if nums is None or len(nums) == 0:
                return -1
            nlen = len(nums)
            
            if target <= nums[0]:
                return 0
            if target > nums[nlen - 1]:
                return nlen
                
            lo = 0
            hi = nlen - 1
            mid = 0
            
            while lo < hi:
                mid = lo + (hi - lo)/2
                if nums[mid] == target:
                    return mid
                elif nums[mid] > target:
                    hi = mid
                    if hi == lo + 1:
                        return lo + 1
                else:
                    lo = mid
                    if lo == hi - 1:
                        return hi
                        
            
            return -1

Log in to reply
 

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