[LeetCode]easy - Search Insert Position - python

题目要求: 

要求在给定的有序数组中查找目标值,如果找到target则返回索引, 如果没有则返回它应该插入的位置的索引。限定条件,时间复杂度为O(log n)。

Problem Description:

Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity.

题目链接

思路:

这道题是别致一点的二分查找题,且二分查找的时间复杂度符合这道题的限制条件。

首先,将数组中间位置的值和target比较,如果两者相等则查找成功;否则利用中间位置将数组分成前、后两个子数组,如果中间位置的值大于target,则进一步查找前一子数组,否则进一步查找后一子数组。

重复以上过程,直到找到target,使查找成功,或直到子数组不存在为止,此时查找不成功。

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        length = len(nums)
        left = 0
        right = length - 1
        if nums is None or target < nums[0]:
            return 0
        elif target > nums[-1]:
            return length
        else:        
            while left <= right:
                mid = int((left + right)/2)
                if target < nums[mid]:
                    right = mid - 1
                elif target > nums[mid]:
                    left = mid + 1
                else:
                    return mid
            return left

结果如下:

二分查找:

二分查找又称折半查找,它是一种效率较高的查找方法。二分查找要求:线性表是有序表,即表中结点按关键字有序,并且要用向量作为表的存储结构。不妨设有序表是递增有序的。

本质上是一个不断缩小搜索空间的过程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值