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))
全部评论

相关推荐

05-25 10:45
西华大学 Java
Frank_zhang:没实习一个项目肯定不够,可以再做一个轮子,技术栈再补一个mq,微服务,整体再换个简历模板,暑期尽量再找一个日常实习
点赞 评论 收藏
分享
抱抱碍事梨a:三点建议,第一点是建议再做一个项目,把自我介绍部分顶了,第二点是中南大学加黑加粗,第三点是建议加v详细交流
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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