Leetcode35 Search Insert Position 解题思路(python)
本人编程小白,如果有写的不对、或者能更完善的地方请个位批评指正!
这个是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)的更多相关文章
- LeetCode: Search Insert Position 解题报告
Search Insert Position Given a sorted array and a target value, return the index if the target is fo ...
- 【LeetCode】35. Search Insert Position 解题报告(Java & Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 二分查找 日期 题目地址:https://leetc ...
- [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 ...
- LeetCode35 Search Insert Position
题目: Given a sorted array and a target value, return the index if the target is found. If not, return ...
- 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 ...
- [Leetcode][Python]35: Search Insert Position
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 35: Search Insert Positionhttps://oj.le ...
- Leetcode 二分查找 Search Insert Position
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie Search Insert Position Total Accepted: 14279 T ...
- [LeetCode] 035. Search Insert Position (Medium) (C++)
索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 035. Sea ...
- [LC]35题 Search Insert Position (搜索插入位置)
①英文题目 Given a sorted array and a target value, return the index if the target is found. If not, retu ...
随机推荐
- Jquery+H5验证数据(不是表单验证啊 )
啥也不说了 直接上代码 1.我将所有需要验证的控件都加上了 required(类名自己定吧没啥讲究) class 2.所有的控件都加上了 data-vname的H5自定义属性(名称自个定义吧) ...
- django filter or 多条件查询
功能:django中实现多条件查询 或关系: from django.db.models import Q return qs.filter(Q(notice_to_group__contains=' ...
- 《AlwaysRun!》第一次作业:团队亮相
项目 内容 这个作业属于哪个课程 2016级软件工程(西北师范大学) 这个作业的要求在哪里 实验五 团队作业1:软件研发团队组建 团队名称 Always Run! 作业学习目标 熟悉软件的开发流程与 ...
- WebForm应用log4net记录错误日志——使用线程列队写入
我的项目结构如下图: 日志帮助类库需要log4net包:工具—NuGet包管理器—管理解决方案NuGet程序包 线程日志帮助类 FlashLogger.cs 代码 using System; usin ...
- 控制请求重复提交的方法总结(Token)
重复提交的定义: 重复提交指的是同一个请求(请求地址和请求参数都相同)在很短的时间内多次提交至服务器,从而对服务器造成不必要的资源浪费,甚至在代码不健壮的情况还会导致程序出错. 重复提交的原因或触发事 ...
- kivy sdl2 - ImportError: DLL load failed: 找不到指定的模块。
kivy version : windows:win python version:3.6 sdl2 - ImportError: DLL load failed: 找不到指定的模块. 运行以下dem ...
- winform自定义控件中其他遮挡控件点击事件
自定义控件在其他窗口调用时,里面的lable阻挡了控件的点击事件 解决方法 自定义控件中lable的 点击事件 private void Lable1_Click(object sender, Eve ...
- WebAPI常见的鉴权方法,及其适用范围
在谈这个问题之前,我们先来说说在WebAPI中保障接口请求合法性的常见办法: API Key + API Secret cookie-session认证 OAuth JWT 当然还有很多其它的,比如 ...
- Unity Button事件的简洁处理
看到很多人依然还是通过最原始的方法给button绑定事件并处理,这种通过Find往子集一个个的查找,获取到后再绑定事件这种操作很费事,有些人则是对查找对象写了个方法自动往子集遍历更方便获取对象,但还是 ...
- 转载 linux基本操作
转载地址 https://segmentfault.com/a/1190000014840829 前言 只有光头才能变强 这个学期开了Linux的课程了,授课的老师也是比较负责任的一位.总的来说也算是 ...