【Leetcode】35. Search Insert Position

【Leetcode】35. Search Insert Position

class Solution(object):
    def searchInsert(self, nums, target):
        """
        duplicates condition should be take care of

        The question itself is not worth to record , but the thinking progress of how we control the border should be valued.
        The main idea to control the border I think should be related to what the question need we do.
        for eg, in this question , we need to find the place to insert current number, that is find the first number whose number just more than current number
        so when we do binary research , if nums[middle] more than current number n, what we should do to update the low? middle or middle +1
        because we need to find the first number more than n, and nums[middle] is more than n, so the index middle may be the result and we certianly must not to drop it
        so we need update low to middle instead of middle +1
        And if nums[middle] < target, that is middle must not be the result , so we need drop it , what will happen if we don't drop it ?
        for eg, if we only have two elements [a,b](a < b) we need to find a number's (n a < n < b) insert place
        middle = (0 + 1) //2 =0 and nums[0] < n , the we update low to middle , so the new low and high still is 0,1,
        it result in a endless loop
        """
        if target < nums[0]:
            return 0
        if target > nums[-1]:
            return len(nums)

        start, end  = 0, len(nums)
        while(start < end):
            print(start, end)
            middle = (start + end) //2
            if nums[middle] == target:
                return middle
            elif nums[middle] > target:
                end = middle
            else:
                # nums[middle] < target
                start = middle
        return start