本人编程小白,如果有写的不对、或者能更完善的地方请个位批评指正!

这个是leetcode的第35题,这道题的tag是数组,python里面叫list,需要用到二分搜索法

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 1:

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

Example 2:

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

Example 3:

Input: [1,3,5,6], 7Output: 4

Example 4:

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

(https://leetcode.com/problems/search-insert-position/)

思路:

方法一:

这道题目最直观的解法肯定是一次循环for循环,因为数组(list)已经是排好序得了,考虑两种情况:

第一种:target不在数组中,那么比数组中最大的数字大的时候,他的返回值是数组的长度+1(即python中的len(array)),比数组中最小的数字小的在第二种情况中考虑,返回值是0

第二种:只要找出来第一个比target大的数字,那么这个数字所对应的位置就是返回值,

时间复杂度:O(n)

Python 代码实现:

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)

        for i in range(len(nums)):

            if nums[i] >= target:

                return i

代码实现起来其实是很容易的,只有五行,但我用的第一种方法做完之后只beat了2.8%的提交者(2018/12/22,因为这个“%”肯定随着时间的推移而改变),说明肯定不是最优解

方法二:

既然是排好序的数组,那么我们知道二分搜索法的时间复杂度是log(n),(如果有人需要复习二分搜索发的话请见参考文献)

类似于方法一的第二种情况,我们是希望找到数组中第一个比target大的数字

这里我考虑的是以下几种情况:

第一种:target小于num[0]或者大于num[len-1]

第二种:target等于数组中的某数,即被二分搜索法找到

第三种,target在num[0]和num[len-1]中间,但不等于数组中的任何一个数

时间复杂度:log(n)

Python 代码实现:

class Solution(object):

    def searchInsert(self, nums, target):

        """

        :type nums: List[int]

        :type target: int

        :rtype: int

        """

        if target <= nums[0]:

            return 0

        elif target > nums[len(nums)-1]:

            return len(nums)

        low,high = 0, len(nums)-1

        while low <= high:

            mid = (low+high) // 2

            if target > nums[mid]:

                low = mid + 1

            elif target < nums[mid]:

                high = mid - 1

            else:

                return mid

        if target < nums[mid]:

            return mid

        elif target > nums[mid]:

            return mid+1

    if __name__ == '__main__':

        nums = [1,2,3,4,6]

        target = 5

        print(searchInsert(0,nums,target))

我这里用的是while实现的二分搜索法,提交之后发现竟然还只是击败了32%的提交者,但感觉在时间复杂度上已经是最优的解了,

如果还有更好的解法欢迎大家留言或私信,谢谢 : )

参考文献:

1. 复习二分法连接:https://blog.csdn.net/djd1234567/article/details/45676829

Leetcode35 Search Insert Position 解题思路(python)的更多相关文章

  1. LeetCode: Search Insert Position 解题报告

    Search Insert Position Given a sorted array and a target value, return the index if the target is fo ...

  2. 【LeetCode】35. Search Insert Position 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 二分查找 日期 题目地址:https://leetc ...

  3. [LeetCode] 35. Search Insert Position 解决思路

    Given a sorted array and a target value, return the index if the target is found. If not, return the ...

  4. LeetCode35 Search Insert Position

    题目: Given a sorted array and a target value, return the index if the target is found. If not, return ...

  5. 35. Search Insert Position@python

    Given a sorted array and a target value, return the index if the target is found. If not, return the ...

  6. [Leetcode][Python]35: Search Insert Position

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 35: Search Insert Positionhttps://oj.le ...

  7. Leetcode 二分查找 Search Insert Position

    本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie Search Insert Position Total Accepted: 14279 T ...

  8. [LeetCode] 035. Search Insert Position (Medium) (C++)

    索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 035. Sea ...

  9. [LC]35题 Search Insert Position (搜索插入位置)

    ①英文题目 Given a sorted array and a target value, return the index if the target is found. If not, retu ...

随机推荐

  1. python 的xlrd模块

    一.安装 ♦ python官网下载http://pypi.python.org/pypi/xlrd模块安装. ♦或者在cmd窗口  pip install  xlrd 二.使用 1.导入模块: imp ...

  2. iTerm2使用技巧

    iTerm2实用技巧 搜索及文本复制 使用“cmd+f”可以调出搜索框进行文本搜索,然后有个很奇妙的快捷键“tab”键,使用它后会自动高亮当前文本后面的内容.最后按enter键将高亮文本复制到剪切板上 ...

  3. NoteBook学习(一)-------- Zeppelin VS Jupyter

    notebook1.mdhtml, body {overflow-x: initial !important;}html { font-size: 14px; color: rgb(51, 51, 5 ...

  4. python requests库爬取网页小实例:ip地址查询

    ip地址查询的全代码: 智力使用ip183网站进行ip地址归属地的查询,我们在查询的过程是通过构造url进行查询的,将要查询的ip地址以参数的形式添加在ip183url后面即可. #ip地址查询的全代 ...

  5. java redispool测试类保存

    这两天睡眠不足,今晚吃完饭,肚子烦躁的很,迟迟进入不了代码的状态,强打精神,又赶上处理了几个编辑器的报错,等到真正面对问题的时候又是晚上十一点, 晚上十一点是幸运点,到这个点无关问题都能解决完毕进入调 ...

  6. select2插件用法

    1.修改默认查询方法,使其可以根据value查询 this.element.select2({ allowClear: true, matcher: function (term, text, ele ...

  7. 直接插入排序(js版)

    直接插入排序(从小到大) 基本思想:将一个记录插入到已经排好序的有序表中,得到一个新的,记录数加1的有序表. function insertSort(arr){ var i,j,temp=0; for ...

  8. 字符模式console usb串口安装centos

    黄色部分是使用console口安装centos需要使用text模式,可以参考前文,同时镜像路径也是需要指定的,来自/dev/sda4 U盘 setparams 'Install CentOS 7' l ...

  9. python 字符串 转 bit, bitarray 异或加密

    Python中异或加密要将str 转为 bitarray, 提示: int类型和纯数字的字符串也可以异或处理, 可能更方便 from bitarray import bitarray def str2 ...

  10. awk命令小结

    先在此至敬朱双印老师,博客写得很详细:http://www.zsythink.net/archives/tag/awk/ 这是朱双印老师关于awk博客的链接,强力推荐给大家   AWK一般在网上说是一 ...