[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 ...
随机推荐
- 4、css盒模型和文本溢出
4:css盒模型和文本溢出 学习目标 1.认识盒子模型 2.盒子模型的组成部分 3.学习盒子模型的相关元素 margin padding 4.文本溢出相关的属性 一.css属性和属性值的定义 盒模型是 ...
- ThinkPHP框架 基础 链接数据库
在第一次成功访问应用入口文件的时候,会显示出一个系统默认的欢迎页面并自动在APPLication文件夹里生成三个文件夹,如下,第一次访问应用文件路径:localhost/tr/index.php ...
- for循环 例子
<script type="text/javascript"> //循环 for循环 //循环操作某一个功能(执行某段代码) //四要素 1.循环初始值 2.循环条件 ...
- asp.net 访问页面访问统计实现
0x00.背景: 1.用户访问网站所有页面就将访问统计数加1 ,按每月存放. 2.站点并没有用到母版面来实现,所有各个页面都很独立. 3.网站是很早这前的网站,尽量省改动以前的代码.按理说我们应该做一 ...
- [dpdk] TSC , HPET, Timer, Event Timer,RDTSCP
关于dpdk timer跨越CPU core调度的准确性问题 首先dpdk的timer接口里边使用 cpu cycle来比较时间.根据之前的内容 [dpdk] dpdk --lcores参数 当一个E ...
- Flink - CoGroup
使用方式, dataStream.coGroup(otherStream) .where(0).equalTo(1) .window(TumblingEventTimeWindows.of(Time. ...
- dp的斜率优化
对于刷题量我觉得肯定是刷的越多越好(当然这是对时间有很多的人来说. 但是在我看来我的确适合刷题较多的那一类人,应为我对知识的应用能力并不强.这两天学习的内容是dp的斜率优化.当然我是不太会的. 这个博 ...
- 内部排序->选择排序->树形选择排序
文字描述 树形选择排序又称锦标赛排序; 比如,在8个运动员中决出前3名至多需要11场比赛, 而不是7+6+5=18场比赛(它的前提是甲胜乙,乙胜丙,则甲必能胜丙) 首先对n个记录的关键字进行两两比较, ...
- Python开发【模块】:aiohttp(二)
AIOHTTP 1.文件上传 ① 单个文件上传 服务端 async def post(self, request): reader = await request.multipart() # /!\ ...
- 机器Coding For WPF
declare @modelcode varchar(90)='AutoProjectType'declare @ns varchar(90)='WpfApplication'declare @dat ...