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的更多相关文章

  1. [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 ...

  2. 【LeetCode】701. Insert into a Binary Search Tree 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  3. 【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 ...

  4. [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 ...

  5. LeetCode题解之Insert into a Binary Search Tree

    1.题目描述 2.分析 插入算法. 3.代码 TreeNode* insertIntoBST(TreeNode* root, int val) { insert(root, val); return ...

  6. [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 ...

  7. [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. ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. D - Wireless Network

    来源poj2236 An earthquake takes place in Southeast Asia. The ACM (Asia Cooperated Medical team) have s ...

  2. B - Hamburgers

    Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own han ...

  3. rxjs 常用的静态操作符

    操作符文档 API create const { Observable } = require('rxjs'); // 创建 Observables var observable = Observab ...

  4. 170823、SQL Update多表联合更新的方法

    SQL Update多表联合更新的方法 (1) sqlite 多表更新方法 update t1 set col1=t2.col1 from table1 t1 inner join table2 t2 ...

  5. PHP数组总结,,PHP面向对象思维思路。

    <?php //定义数组 $attr = array(); $attr[] = ; //索引数组 $attr = array(,,,); //关联数组 $attr = array("c ...

  6. python金融与量化分析------Matplotlib(绘图和可视化)

    -----------------------------------------------------------Matplotlib:绘图和可视化------------------------ ...

  7. redis数据持久化的两种方式

    1,AOF AOF持久化以日志的形式记录服务器所处理的每一个写.删除操作,查询操作不会记录,以文本的方式append记录,可以打开文件看到详细的操作记录.(相同数量的数据集而言,AOF文件通常要大于R ...

  8. 新装的arcgis10.5特别卡

    在之前装过arcgis10.5,用了一段时间感觉还不错.  由于二次开发要用到AO,当时缺少开发包,所以用了10.4.  现在跟师傅合作开发,要跟他保持一致,所以用了arcgis10.5.  但是装的 ...

  9. windows hook 钩子

    windows  hook  钩子 场景: 1.打印机 Ctrl+P弹出支付窗口,付款成功后打印

  10. An optimizer that trains as fast as Adam and as good as SGD. https://www.luolc.com/publications/ad…

    设立3个指针pa.pb和pc,其中pa和pb分别指向La表和Lb表中当前待比较插入的结点,而pc指向Lc表中当前最后一个结点:若pa->data<=pb->data,则将pa所指结点 ...