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

这个是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. git clone失败

    操作: $ git clone https://github.com/zjun615/DragListView.gitCloning into 'DragListView'...fatal: unab ...

  2. airTest 应用到项目并优化

    之前已经介绍了airTest的原理,该文主要指引大家能够将airTest框架应用到具体的测试项目当中去. 首先要考虑的是: 1. 你是用airTest 去做什么自动化 (android, ios, w ...

  3. Python中日期和时间格式化输出的方法

    本文转自:https://www.jb51.net/article/62518.htm 本文实例总结了python中日期和时间格式化输出的方法.分享给大家供大家参考.具体分析如下: python格式化 ...

  4. [leetcode]272. Closest Binary Search Tree Value II二叉搜索树中最近的值2

    Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...

  5. Boto3

    https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.htmlboto3 安装pip install bot ...

  6. Python语言学习之C++调用python

    C++调用python 在C/C++中嵌入Python,可以使用Python提供的强大功能,通过嵌入Python可以替代动态链接库形式的接口,这样可以方便地根据需要修改脚本代码,而不用重新编译链接二进 ...

  7. HDU 6161.Big binary tree 二叉树

    Big binary tree Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)T ...

  8. nginx集成环境下载

    https://visual-nmp.en.softonic.com/download

  9. Go的并发调度原理

    Go语言是为并发而生的语言,Go语言是为数不多的在语言层面实现并发的语言:也正是Go语言的并发特性,吸引了全球无数的开发者.   并发(concurrency)和并行(parallellism) 并发 ...

  10. python3 第三十一章 - 模块

    1.什么是模块 如果从Python解释器退出并再次输入,您所做的定义(函数和变量)将丢失.因此,如果要编写一个稍长的程序,最好使用文本编辑器为解释器准备输入,并以该文件作为输入运行它.这称为创建脚本. ...