[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 ...
随机推荐
- Django----Admin流程
Admin执行步骤 启动文件: 1:创建app-----stark 2:在每个app中创建stark 3:django----admin---- 4:在stark中写入:--------------- ...
- 如何打jar包 学习笔记
jar包是由.class文件压缩而成.要查看jar包中的内容,使用压缩工具 解压缩即可.也可以做修改,并重新打成jar包.总结一下最近学到的一些打jar包的方法: 一.DOS下使用jar命令 打jar ...
- iOS10原生的语音转文字功能
#import <Foundation/Foundation.h> #import <Speech/Speech.h> @interface SpeechListener : ...
- zabbix自动发现主机并加入组绑定模板
在被监控主机多的情况下,怎样将这些主机加入zabbix server进行监控呢?下面将介绍下zabbix自动发现功能 1.创建自动发现规则 创建“规则名称,配置ip范围及检查方式”,点击“增加”,完成 ...
- 函数调用堆栈及活动记录 堆栈溢出 stack overflow
小结: 1.当被调函数返回主调函数时,被调函数的 活动记录-activation record / 堆栈帧-stack frame 被 弹出-popping 程序执行栈-program executi ...
- [development][C] linux 设置线程名称
两个API, 都是linux的. 不是POSIX, 是GNU? 傻傻搞不清楚. 1. pthread_setname_np / pthread_setname_np 2. ptctl 带 PR_GE ...
- [security] security engine things
1. luarock luarock 之于 lua,就好比 pip 之于 python https://luarocks.org/ 2. lua的库 [root@base package]# ls ...
- JDBC---Mysql(2)
SQL注入攻击: 用户可以提交一段数据库查询代码,根据程序返回的结果,获得某些他想知道的数据,这就是所谓的SQL注入攻击, 例如:判断username='a' or 'a'='a'; true从而为 ...
- Apache Common Math Stat
http://commons.apache.org/proper/commons-math/userguide/stat.html mark DescriptiveStatistics maint ...
- 关于lis的方案数
求lis的时候呢,我想n^2的做法是很简单的,二分的话除了最长不上升或最长不下降子序列不好求之外(毕竟要注意细节)于是从中发现了,求lis真正的序列也是十分不好求出的尤其是字典序最大的不上升序列了,什 ...