LeetCode - 35: Search Insert Position

35、Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.

Example:

Input: [1,3,5,6], 5
Output: 2

Solution - Python:

#!/usr/bin/env python
# -*- coding = utf-8 -*-

""" @ Create Time: 2018/04/30 @ Author: songpo.zhang @ Target: """

def searchInsert(nums, target):
    left, right = 0, len(nums)-1
    while left <= right:
        mid = int((left + right) / 2)
        if target == nums[mid]:
            return mid
        elif target > nums[mid]:
            left = mid + 1
        else:
            right = mid -1
        return left

if __name__ == "__main__":
    print(searchInsert([1, 3, 5, 6], 5))
全部评论

相关推荐

政委qqq:这道题在算法竞赛里唯一考的就是高精度,但是只能难住C++这类语言,Python直接a+b秒天秒地
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务