美文网首页
54. LeetCode 35. 搜索插入位置

54. LeetCode 35. 搜索插入位置

作者: 月牙眼的楼下小黑 | 来源:发表于2019-02-11 20: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
  • 其他解法

暂略。

相关文章

网友评论

      本文标题:54. LeetCode 35. 搜索插入位置

      本文链接:https://www.haomeiwen.com/subject/bphceqtx.html