[LeetCode] 35. Search Insert Position_Easy tag: Binary Search
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], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
Update: 04/13/2019, 添加第4种方式,个人认为是面试过程中最适合用的。
思路就是Binary Search, 找到first position s.t A[i] >= target
Code
1) 利用python的built-in function bisect.bisect_left
class Solution:
def searchInsert(self, nums, target):
return bisect.bisect_left(nums, target)
2) 利用python的built-in function bisect.bisect
class Solution:
def searchInsert(self, nums, target):
return nums.index(target) if target in nums else bisect.bisect(nums, target)
3) basic 做法, first position s.t A[i] >= target
if not nums: return 0
l, r = 0, len(nums)-1
while l + 1 < r:
mid = l + (r - l)//2
if nums[mid] < target:
l = mid
elif nums[mid] > target:
r = mid
else:
return mid # 因为没有duplicates
if nums[l] >= target:
return l
elif nums[r] >= target:
return r
else:
return r+1 # 因为有可能比最大的还大
4) 还是用binary search的模板,只不过要注意左右边界,尤其是左边界时,如果小于或者等于nums中的最小值,都要返回0;但是右边界如果大于是len(n),如何是相等则是len(n)- 1。
class Solution:
def searchInsert(self, nums, target):
l, r = 0, len(nums) - 1
if not nums or nums[l] >= target:
return 0
if nums[r] < target:
return len(nums)
while l + 1 < r:
mid = l + (r - l)//2
if nums[mid] > target:
r = mid
elif nums[mid] < target:
l = mid
else:
return mid
return r # 这里直接return r 是因为边界已经考虑,所以最起始的r要么是等于target,要么是> target, 而l 也以为边界已经考虑的原因,
所以最起始的l肯定是小于target的,所以不可能是l(另外if语句里只有在nums[mid] < target 才会改变l)所以一定是r。
[LeetCode] 35. Search Insert Position_Easy tag: Binary Search的更多相关文章
- [LeetCode] 278. First Bad Version_Easy tag: Binary Search
You are a product manager and currently leading a team to develop a new product. Unfortunately, the ...
- 【LeetCode】701. Insert into a Binary Search Tree 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- 【leetcode】701. Insert into a Binary Search Tree
题目如下: Given the root node of a binary search tree (BST) and a value to be inserted into the tree, in ...
- [LeetCode] 69. Sqrt(x)_Easy tag: Binary Search
Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a no ...
- LeetCode题解之Insert into a Binary Search Tree
1.题目描述 2.分析 插入算法. 3.代码 TreeNode* insertIntoBST(TreeNode* root, int val) { insert(root, val); return ...
- [LeetCode] 162. Find Peak Element_Medium tag: Binary Search
A peak element is an element that is greater than its neighbors. Given an input array nums, where nu ...
- [LeetCode] 33. Search in Rotated Sorted Array_Medium tag: Binary Search
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e. ...
- [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- [LeetCode] 108. Convert Sorted Array to Binary Search Tree 把有序数组转成二叉搜索树
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. Fo ...
随机推荐
- day_5.25py
作用域
- Java基础语法<七> 对象与类 封装
笔记整理 来源于<Java核心技术卷 I > <Java编程思想> 1. 类之间的关系 1.1 依赖 users– a 是一种最明显的.最常见的关系.如果一个类的方法操作另一个 ...
- ajax传输中文参数乱码,本地使用tomcat不乱码,liunx+weblogic乱码
公司项目有个问题,ajax请求含中文,无论是post方式还是get方式.本地使用tomcat不乱码,liunx+weblogic都乱码.并且用以往encodeURIComponent()并在后台解码之 ...
- 主席树||可持久化线段树||离散化||[CQOI2015]任务查询系统||BZOJ 3932||Luogu P3168
题目: [CQOI2015]任务查询系统 题解: 是一道很经典的题目.大体思路是抓优先级来当下标做主席树,用时刻作为主席树的版本.然而优先级范围到1e7去了,就离散化一遍.然后把每个事件的开始(s). ...
- Unable to cast object of type 'System.Int32' to type 'System.Array'.
x 入职了新公司.最近比较忙...一看博客...更新频率明显少了...罪过罪过... 新公司用ASP.NET MVC 遇上一个错误: Unable to cast object of type 'Sy ...
- RabbitMQ in Depth札记——AMQ协议
RPC传输 作为AMQP的实现,RabbitMQ使用RPC(remote procedure call)模式进行远程会话.而不同于一般的RPC会话--客户端发出指令,服务端响应,但服务端不会向客户端发 ...
- 20165311 实验一 Java开发环境的熟悉
一.实验报告封面 课程:Java程序设计 班级:1653班 姓名:李嘉昕 学号:20165311 指导教师:娄嘉鹏 实验日期:2018年4月2日 实验时间:13:45 - 15:25 实验序号:3 实 ...
- python-mysql数据库导表存excel后发邮件(实例2)
需求:用户输入mysql数据库中某表名,将此表导入到excel中,将导出文件以邮件形式发出 设计思路: 1连接数据库 2读取表头(cur.description--获取表头,函数返回二维元组,采用列表 ...
- radio样式的写法,单选和多选如何快速的改变默认样式,纯CSS,
一.纯CSS写法改变单选框的默认选择样式,用背景图片代替 input[type='radio']:radio:before { content: '';//这里需要有 width: 20px; hei ...
- 常用css属性
一.常用css属性 (1) *block(区块) 行高 line-height:数值 | inherit | normal;字间距 letter-spacing: 数值 | inherit | nor ...