码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--035--搜索插入位置

时间:2018-07-23 22:07:27      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:insert   code   range   style   目标   round   etc   int   return   

问题描述:

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

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

方法1:for 循环

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if target > nums[-1]:
            return len(nums)
        for i in range(len(nums)):
            if nums[i] == target:
                return i
            if nums[i] > target:
                return i

方法2:二分法查找

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

 2018-07-23 18:27:11

LeetCode--035--搜索插入位置

标签:insert   code   range   style   目标   round   etc   int   return   

原文地址:https://www.cnblogs.com/NPC-assange/p/9357025.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!