进行二分查找课程回顾与总结,包括以下几个方面,二分法的模板总结和解题思路、应用。

二分法模板总结classical binary search:

1. 必须要做的排除极端情况,也就是数组(用A表示)不存在即A == None或者 A为空,即len(A) == 0 的情况。

2. 二分法核心找的是mid值,并判断这个mid是否跟我们要找的target一致,或者和target之间的关系,所以要先判断start和end。为start和end赋值,start = 0, end = len(A) - 1

3. 之后就是要进行while循环,目的是用一次次的二分来找出是否存在target或者target的位置、范围等问题,条件是start + 1 < end来避免死循环

并有 mid = start + ( end - start ) / 2 来避免溢出

4. 判断A[mid] 与 target的关系,及采取怎样的赋值操作来保留有解的一半,即start == mid 或者 end == mid

5. 可能A[start] 与 A[end]的值与target相同,但是已经使 start + 1 < end 这个条件为False,所以在循环外还要判断这两个值是否和target一致。

6. 如果都不相等的话则返回空

下面,给出classical binary search的解法,这是简单而典型的binary search on index的问题

class Solution:
# @param {int[]} A an integer array sorted in ascending order
# @param {int} target an integer
# @return {int} an integer
def findPosition(self, A, target):
# they are different
if A is None or len(A) == 0:
return -1
# set start and end
end = len(A) - 1
start = 0
# while loop, use start + 1 < end to avoid dead loop
while (start + 1 < end):
mid = start + ( end - start ) / 2
if A[mid] == target:
return mid
elif A[mid] > target:
# start..mid..end, target in start..mid
end = mid
else:
start = mid
if A[start] == target:
return start
if A[end] == target:
return end
return -1

由经典算法可以展开到the first position or the last position,都是binary search on index的典型例子,在这两种中即使找到了相应的元素为了判断是否是最开始或者最后的位置,在第四第五步要有所不同~以last position为例

while (start + 1 < end):
mid = start + ( end - start ) / 2
if A[mid] == target:
start = mid
elif A[mid] > target:
# start..mid..end, target in start..mid
end = mid
else:
start = mid
if A[end] == target:
return end
if A[start] == target:
return start

比较类似的像 search a 2D matrix 问题,只是把二维数组展开成一个一维数组,继续采用上面的二分法模板就可以解

class Solution:
"""
@param matrix, a list of lists of integers
@param target, an integer
@return a boolean, indicate whether matrix contains target
"""
def searchMatrix(self, matrix, target):
if matrix is None or len(matrix) == 0:
return False
m = len(matrix)
n = len(matrix[0])
start = 0
end = m * n - 1
while(start + 1 < end):
mid = start + (end - start) / 2
line = mid / n
column = mid % n
if matrix[line][column] == target:
return True
elif matrix[line][column] < target:
start = mid
else:
end = mid
if matrix[(start / n)][(start % n)] == target:
return True
if matrix[(end / n)][(end % n)] == target:
return True
return False

search insert position 只要把握住二分法一个重要的特性,就是判断条件,就可以转化为找first position >= target 的问题

class Solution:
"""
@param A : a list of integers
@param target : an integer to be inserted
@return : an integer
"""
def searchInsert(self, A, target):
# find the position whose value is equal or more than target
# only consider no duplicates conditions
if A is None or len(A) == 0:
return 0
start = 0
end = len(A) - 1
while(start + 1 < end):
mid = start + (end - start) / 2
if A[mid] >= target:
end = mid
else:
start = mid
if A[start] >= target:
return start
if A[end] >= target:
return end
# a condition that the target is more than all of the elements in array
if A[end] < target:
return end + 1
return -1

二分查找总结及部分Lintcode题目分析 1的更多相关文章

  1. 二分查找总结及部分Lintcode题目分析 2

    Search in a big sorted array,这个比之前的二分法模板多了一个很不同的特性,就是无法知道一个重要的条件end值,也是题目中强调的重点 The array is so big ...

  2. 二分查找总结及部分Lintcode题目分析 4

    二分法不只能像之前的记录,可以找到index~第二种类型是找到二分答案.有以下几个例子,都是之前二分法的扩展,不再赘述,只记录下忽略的点,以后回顾多注意~ 1. wood cut class Solu ...

  3. 二分查找总结及部分Lintcode题目分析 3

    Search in rotated sorted array,题目中也给出了相应的例子,就是在sorted array某个节点发生了翻转(ie.0 1 2 4 5 6 7 might become 4 ...

  4. 二叉树总结及部分Lintcode题目分析 1

    1. 遍历问题 Preorder / Inorder / Postorder preorder: root left right inorder: left root right postorder: ...

  5. Find Minimum in Rotated Sorted Array 典型二分查找

    https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/ Suppose a sorted array is rot ...

  6. HDU 3763 CD【二分查找】

    解题思路:给出两个数列an,bn,求an和bn中相同元素的个数因为注意到n的取值是0到1000000,所以可以用二分查找来做,因为题目中给出的an,bn,已经是单调递增的,所以不用排序了,对于输入的每 ...

  7. POJ 3273 Monthly Expense二分查找[最小化最大值问题]

    POJ 3273 Monthly Expense二分查找(最大值最小化问题) 题目:Monthly Expense Description Farmer John is an astounding a ...

  8. 二分查找里的upper bound与lower bound的实现与分析

    1. 问题引入 最近参选了学堂在线的课程数据结构(2015秋).课程由清华大学的邓俊辉老师主讲,在完成课后作业时,遇到了这样一个题目范围查询.在这个题目中,我需要解决这样一个子问题:给定了一组已经排好 ...

  9. (二分查找 拓展) leetcode 34. Find First and Last Position of Element in Sorted Array && lintcode 61. Search for a Range

    Given an array of integers nums sorted in ascending order, find the starting and ending position of ...

随机推荐

  1. CentOS7.6编译安装openssl-1.1.1c

    卸载旧版本OpenSSL # which openssl/usr/bin/openssl# mv openssl openssl.oldrm -rf /etc/ssl #删除配置文件 CentOS7. ...

  2. Java用集合实现斗地主发牌

    本文以java双列集合HashMap为核心实现发牌操作:                                思路: 1.准备牌:创建一个Map集合,存储牌的索引和组装好的牌 创建一个lis ...

  3. springboot启动时过滤不需要注入的类

    在springbootApplication启动类上加入注解 @ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterTy ...

  4. Delphi中关于菜单的几个技巧

    -- 1将菜单项移到菜单栏的最右边 在一些应用程序中,常把一些特殊的菜单项放在菜单栏的最右边(如WPS2000 中的"定制界面"菜单,一些应用程序的帮助菜单),这些菜单项放在菜单栏 ...

  5. hdu多校第五场1002 (hdu6625) three arrays 字典树/dfs

    题意: 给你两个序列a,b,序列c的某位是由序列a,b的此位异或得来,让你重排序列ab,找出字典序最小的序列c. 题解: 如果能找到a,b序列中完全一样的值当然最好,要是找不到,那也尽量让低位不一样. ...

  6. Greenplum(PostgreSql)中函数内游标的使用实例

    直接上代码,具体整体函数定义就不上了,只写关键部分: --定义两个变量 DECLARE CCUR REFCURSOR; -- 游标变量 RECORD1 RECORD; -- 记录变量,用来存储游标遍历 ...

  7. [转] 多个文件目录下Makefile的写法

    1.前言 目前从事于linux下程序开发,涉及到多个文件,多个目录,这时候编译文件的任务量比较大,需要写Makefile.关于Makefile的详细内容可以参考网上流传非常广泛的<跟我一起写Ma ...

  8. element-ui表格合计不显示&被遮挡问题

    step1:修改全局样式 .el-table{ overflow:visible !important; } .el-card__body { padding: 20px 20px 50px 20px ...

  9. importError:cannot import name imsave/imread等模块

    首先要先看相应的库是否已经安裝成功 pip install numpy pip install pillow pip install scipy 都成功安装之后,执行: import scipy.mi ...

  10. fastjson转jackson

    使用fastjson有个内存oom的问题,我们应该尽量使用jackjson,为什么呢?因为fastjson会引发一个oom,很潜在的危险,虽然jackjson的api真的非常好用,对于解析json串来 ...