惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Apple Machine Learning Research
Apple Machine Learning Research
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Security @ Cisco Blogs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
Cyberwarzone
Cyberwarzone
SecWiki News
SecWiki News
Webroot Blog
Webroot Blog
L
LINUX DO - 最新话题
V
Vulnerabilities – Threatpost
T
Troy Hunt's Blog
Cloudbric
Cloudbric
L
LINUX DO - 热门话题
Google DeepMind News
Google DeepMind News
H
Heimdal Security Blog
S
Schneier on Security
NISL@THU
NISL@THU
The Hacker News
The Hacker News
Attack and Defense Labs
Attack and Defense Labs
A
Arctic Wolf
V2EX - 技术
V2EX - 技术
Security Latest
Security Latest
AWS News Blog
AWS News Blog
Scott Helme
Scott Helme
W
WeLiveSecurity
S
Secure Thoughts
Y
Y Combinator Blog
GbyAI
GbyAI
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - Franky
量子位
人人都是产品经理
人人都是产品经理
雷峰网
雷峰网
K
Kaspersky official blog
P
Privacy & Cybersecurity Law Blog
T
Tenable Blog
The GitHub Blog
The GitHub Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
J
Java Code Geeks
Vercel News
Vercel News
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Schneier on Security
Schneier on Security
云风的 BLOG
云风的 BLOG
小众软件
小众软件
Engineering at Meta
Engineering at Meta
宝玉的分享
宝玉的分享
C
CERT Recently Published Vulnerability Notes
Security Archives - TechRepublic
Security Archives - TechRepublic
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Palo Alto Networks Blog

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN Mintty Tips and Configurations Generating Table of Contents for Markdown with Tagbar Convert Python Script to Exe on Windows with Pyinstaller Ubuntu on Windows Missing after Windows Update 使用代理加速 Mac 终端下载速度 My Experience with Several Zsh Plugin Managers 深圳租房小记 How to Install zplug inside Docker Container Why don't settings inside bashrc or bash_profile take effect? Setting Up Locale in Linux 谷歌 Adsense 申请及在 Hugo 中的配置 How to Write Algorithm Pseudo Code in LaTeX Nifty Nvim Techniques That Make My Life Easier -- Series 4 A Few Grammar Questions in Writing How to Read and Write Images with Unicode Paths in OpenCV Creating A Professional Table in LaTeX with booktabs How to Create Proper Folding for Vim/Nvim Configuration Linux Tips and Tricks -- s1 JPEG Image Orientation and Exif How Do I Show the Current File Path In Neovim? JPEG Image Quality in PIL Difference between view, reshape, transpose and permute in PyTorch Convert PIL or OpenCV Image to Bytes without Saving to Disk Fast Movement and Navigation Inside Vim or Neovim Unintuitive Behaviour of Case Sensitivity in Python glob Binding Keys in Zsh 几把机械键盘试用体验 Nvim Autocompletion with Deoplete Converting Markdown to Beautiful PDF with Pandoc Exclusive and Inclusive Motion in Neovim/Vim Nifty Nvim Techniques Which Make My Life Easier -- Series 3 Why Doesn't Jedi Autocompletion Work for Some Methods Vim-like Editing inside Browser Markdown 生成 HTML 时汉字之间出现多余空格问题 小米 9 安装谷歌商店(Google Play Store)与相关配置 Create Mappings That Take A Count in Neovim Spell Checking in Nvim English Words Completion inside Neovim/Vim How to Use Python Inside Vim Script with Neovim Nifty Little Nvim Techniques to Make My Life Easier -- Series 2 Setting up Ultisnips for Neovim Mac 上罗技 M590 鼠标设置 Nifty Little Nvim Techniques to Make My Life Easier -- Series 1 A Complete Guide on Writing LaTeX with Vimtex in Neovim Manipulating Images with Alpha Channels in Pillow Sublime Text Regular Expression Cheat Sheet Cropping Rotated Rectangles from Image with OpenCV Boosting Your Productivity on Terminal with Zsh and Plugins 最新版 Rime 输入法使用 (2022 更新) Display Image with Pillow inside Ubuntu on Windows Faster Directory Navigation with z.lua Cmder Advanced Configurations Nvim-qt Settings on Windows 10 Tmux Plugin Install and Management How to Debug Python Code in Terminal Markdown Writing and Previewing in Neovim -- A Complete Guide Line Number Settings for More Efficient Movement in Neovim 两个大规模中文语料库介绍以及处理 Windows 系统下几款程序员不可不用的神器 我的 2018 阅读清单 A Complete Guide to Neovim Configuration for Python Development How Is Newline Handled in Python and Various Editors? Two Issues Related to ImageFont Module in PIL 在 Listary 中调用 GoldenDict 或欧路词典查单词 Reading and Writing Text Files on Windows The Mathematics behind Font Shapes --- Bézier Curves and More 快速识别图片字体:字体识别工具介绍 Deoplete Failed to Load at Startup after Updating Python neovim Package What Is The Difference between pip, pip3 and pip3.6 Shipped with Anaconda3? Windows 10 系统下 Neovim 安装与配置
从二分搜索实现中的一个 bug 说起
2017-08-27 · via jdhao's digital space

一道二分搜索问题#

下午做了一道 Leetcode 的编程题目,牵扯出了二分搜索实现中需要特别注意的一个问题,题目如下

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, …, n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

这道题可以使用二分搜索来解决,我写出了自认为正确的算法,运行的时候却总是提示 “Time Limit Exceeded”,最初的完整代码如下:

int firstBadVersion(int n) {
  int head = 1, tail = n;
  while (head != tail) {
    int mid = (head + tail) / 2;
    if (isBadVersion(mid)) {
      tail = mid;
    } else {
      head = mid + 1;
    }
  }
  return head;
}

看了一下这道题目的讨论,有人也遇到了同样的问题,解决办法出奇简单。问题的关键就在下面这行看似正确实则错误的代码:

int mid = (head + tail)/2;

改正这个错误也很简单,只需要将上述的写法换成另外一种「形式上等价」的写法:

int mid = head + (tail - head)/2;

之所以说是「形式上等价」是因为,仅从数学推导上来说,上面两种写法结果是一样的,但是计算机科学并不是仅仅是理论,实际中,每种基本数据类型所能表达的数字都是有范围的,如果超过了范围,我们必须考虑整形溢出 (overflow) 问题。假设 headtail 都不超过 int 所能表示的最大正整数(用 INT_MAX 表示),我们并不能保证 head + tail 不超过 INT_MAX,如果两者之和大于 int 类型所能表达的最大的正整数时(该数为 $2^{31}-1$),就会发生溢出;采用第二种写法,由于每一步的计算都没有溢出的可能,最终的结果也不会溢出,因此是更安全的写法。

根据Wiki上的说法,市面上流传的很多二分搜索的实现都存在溢出问题。就连大名鼎鼎的《Programming Pearls》这本书在 1986 年版本上提供的也是第一种写法,直到二十多年后才改为第二种写法;Java 语言中的二分搜索实现起初也存在这个溢出 bug,这个 bug 存在了长达九年才被更正。在计算机发展早期,可能谁也没有预料到,未来的数据量会如此庞大,以至于数组的 index 相加也会造成溢出。Google Research Blog 也曾发布过一篇关于二分搜索实现的博文

当溢出发生,到底会发生什么?#

你可能会好奇,如果发生溢出,到底会有什么后果呢?例如,如果一个 int 类型的数 num 等于 INT_MAX,那么 num 再加上一个正数,会发生什么?C++ 标准对此有明确规定,

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined, unless such an expression is a constant expression, in which case the program is ill-formed. [Note: most existing implementations of C++ ignore integer overflows].

也就是说,num 再加上一个正数,这是 “Undefined behaviour”,任何结果都有可能出现。

上述结果是对于有符号类型 (signed type) 来说的,对于无符号类型 (unsigned type),C++ 标准有如下规定:

This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.

翻译过来就是:无符号类型不会发生溢出。如果一个无符号类型的数加上一个正数产生的结果大于该无符号类型所能表示的最大数,那么最终结果就是原结果与最大数加1取余的结果。

举个例子,假设 numunsigned int 所能表达的最大的数,那么 num + 1 = 0num + 2 = 1,以此类推。一个示例程序如下:

#include <iostream>
#include <limits>
using namespace std;

int main(){
    unsigned int num = std::numeric_limits<unsigned int>::max();

    for (int i = 1; i <= 3; i++){
        unsigned result = num + i;
        cout << result << (i==3?'\n':' ');
    }

    return 0;
}

该程序运行输出结果为:

0 1 2

(全文完)

参考#