二分查找总结及部分Lintcode题目分析 1
进行二分查找课程回顾与总结,包括以下几个方面,二分法的模板总结和解题思路、应用。
二分法模板总结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的更多相关文章
- 二分查找总结及部分Lintcode题目分析 2
Search in a big sorted array,这个比之前的二分法模板多了一个很不同的特性,就是无法知道一个重要的条件end值,也是题目中强调的重点 The array is so big ...
- 二分查找总结及部分Lintcode题目分析 4
二分法不只能像之前的记录,可以找到index~第二种类型是找到二分答案.有以下几个例子,都是之前二分法的扩展,不再赘述,只记录下忽略的点,以后回顾多注意~ 1. wood cut class Solu ...
- 二分查找总结及部分Lintcode题目分析 3
Search in rotated sorted array,题目中也给出了相应的例子,就是在sorted array某个节点发生了翻转(ie.0 1 2 4 5 6 7 might become 4 ...
- 二叉树总结及部分Lintcode题目分析 1
1. 遍历问题 Preorder / Inorder / Postorder preorder: root left right inorder: left root right postorder: ...
- Find Minimum in Rotated Sorted Array 典型二分查找
https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/ Suppose a sorted array is rot ...
- HDU 3763 CD【二分查找】
解题思路:给出两个数列an,bn,求an和bn中相同元素的个数因为注意到n的取值是0到1000000,所以可以用二分查找来做,因为题目中给出的an,bn,已经是单调递增的,所以不用排序了,对于输入的每 ...
- POJ 3273 Monthly Expense二分查找[最小化最大值问题]
POJ 3273 Monthly Expense二分查找(最大值最小化问题) 题目:Monthly Expense Description Farmer John is an astounding a ...
- 二分查找里的upper bound与lower bound的实现与分析
1. 问题引入 最近参选了学堂在线的课程数据结构(2015秋).课程由清华大学的邓俊辉老师主讲,在完成课后作业时,遇到了这样一个题目范围查询.在这个题目中,我需要解决这样一个子问题:给定了一组已经排好 ...
- (二分查找 拓展) 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 ...
随机推荐
- Eureka中的三种角色分别是什么?
Eureka中的三种角色分别是什么? 1.Eureka Server 通过Register.Get.Renew等接口提供服务的注册和发现. 2.Application Service (Service ...
- Centos6.5 安装 LAMP
Centos 安装 LAMP 系统: Centos 6.5 Apache 2.4 + PHP 7.2 + Mysql 5.7 准备工作 centos 查看版本 查看 centos版本 How to C ...
- Linux批量解压缩脚本
#!/bin/bash # 批量解压缩脚本 # 作者: shaohsiung # 时间: // # Store all file names in the tmp directory with the ...
- leetcode-158周赛-5225-最大相等频率
题目描述: 方法: class Solution(object): def maxEqualFreq(self, A): count = collections.Counter() freqs = c ...
- NX二次开发-UFUN创建表达式UF_MODL_create_exp无TAG
NX9+VS2012 #include <uf.h> #include <uf_modl.h> UF_initialize(); //创建一个新的表达式,无TAG UF_MOD ...
- 牛客多校第八场 G Gemstones 栈/贪心
题意: 对于一个序列,把可以把连着三个相同的字母拿走,问最多拿走多少组. 题解: 直接模拟栈,三个栈顶元素相同则答案+1,并弹出栈 #include<bits/stdc++.h> usin ...
- HSF简单实现记录( 基于Ali-Tomcat 开发)
文章目录 声明 注意 提示: Ali-Tomcat 概述 安装 Ali-Tomcat 和 Pandora 并配置开发环境 安装 Ali-Tomcat 和 Pandora 配置开发环境 配置 Eclip ...
- hexo next主题深度优化(三),引入require.js,适配pjax。
文章目录 require.js的好处, hexo next中加入require.js 新建一个main.js作为所有js的入口 pjax的require.js实现 关于require js适配过程中报 ...
- (转)在Source Insight中看Python代码
http://blog.csdn.net/lvming404/archive/2009/03/18/4000394.aspx SI是个很强大的代码查看修改工具,以前用来看C,C++都是相当happy的 ...
- centos 根目录扩容
添加一块磁盘 参考上一篇博文VMware Workstation 添加磁盘 挂载目录(centos) 查看当前磁盘挂载情况 [root@node1 ~]# fdisk -l Disk /dev/sda ...