54. LeetCode 35. 搜索插入位置

2019-02-11  本文已影响9人  月牙眼的楼下小黑

LeetCode475. 供暖器 解法类似。用二分法寻找插入区间。

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

暂略。

上一篇 下一篇

猜你喜欢

热点阅读