python 搜索插入位置

综合编程 2018-05-27 阅读原文

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

示例 1:

输入: [1,3,5,6], 5
输出: 2

示例 2:

输入: [1,3,5,6], 2
输出: 1

示例 3:

输入: [1,3,5,6], 7
输出: 4

示例 4:

输入: [1,3,5,6], 0
输出: 0
class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if target > nums[len(nums) - 1]:
            return len(nums)
        left = 0
        right = len(nums) - 1
        while left < right:
            mid = int(left + (right - left) / 2)
            if nums[mid] == target: 
                return mid
            elif nums[mid] < target:
                left = mid + 1
            else:
                right = mid
        return right
Waiting For You

责编内容by:Waiting For You阅读原文】。感谢您的支持!

您可能感兴趣的

Wallaroo 0.5.3 released Release Notes This is a patch release that includes two very important new features. First, we've released a preview v...
python – 如何子类化大pandasDataFrame? 分类大pandas类似乎是一个常见的需求,但我找不到关于这个问题的参考. (看起来,大pandas的开发人员还在努力: https://github.com/pydata/pandas/issues/60 ). 有一些...
Python 生成个性二维码 一、实验介绍 1.1 实验内容 本课程通过调用MyQR接口来实现生成个人所需二维码,并可以设置二维码的大小、是否在现有图片的基础上生成、是否生成动态二维码。 本课程主要面向Python3初学者。 1.2 知识点 ...
Why is the fileinput.input object not l... In the following code I would expect than python is freeing fileinput.input when I'm return ing in the middle my ...
Neural Japanese Transliteration Neural Japanese Transliteration—can you do better than SwiftKey™ Keyboard? Abstract In this project, I examine ho...