The termination conditions about the binary search
来源:互联网 发布:淘宝网店图标 编辑:程序博客网 时间:2024/05/16 03:09
About some thoughts of binary search:
To avoid some confusion of the binary search, like dead-loop or something.
Every time i write binary search, i always use the 'while' condition like this:
int l = 0;int r = nums.size()-1;while (l < r-1) {// insert the specific code}
This way could definitely eliminate the possibility of dead-loop, like 'l' always be the 'mid', and 'mid' always equals to 'l'.
But this way is not very elegant, so, when could we use the condition like:
while (l<r) {// insert the code here}
To do like this way, we need have condition like:
while (l < r) { int mid = l + (r - l) / 2; if (citations[mid] >= size-mid) r = mid; else l = mid + 1; // The key}
Like the following problem: https://leetcode.com/problems/h-index-ii/
Both solution can reach the correct answer:
// First Editionclass Solution {public: int hIndex(vector<int>& citations) { if ((int)citations.size() == 0) return 0; int size = (int)citations.size(); int l = 0; int r = size - 1; while (l < r-1) { int mid = l + (r - l) / 2; if (citations[mid] >= size-mid) r = mid; else l = mid + 1; } if (citations[l] >= size - l) return size-l; else if (citations[r] >= size - r) return size-r; return 0; }};// We can also write like thisclass Solution {public: int hIndex(vector<int>& citations) { if ((int)citations.size() == 0) return 0; int size = (int)citations.size(); int l = 0; int r = size - 1; while (l < r) { int mid = l + (r - l) / 2; if (citations[mid] >= size-mid) r = mid; else l = mid + 1; } if (citations[r] != 0) return size-r; return 0; }};
0 0
- The termination conditions about the binary search
- all the questions about binary trees
- The implement of Binary Search Tree (JAVA)
- Find the maximum by binary search
- The binary search of distributed programming翻译
- Binary Search:287. Find the Duplicate Number
- about to search or kill the process and the port in the linux
- Binary Search, something about bounds.
- Something about Binary search tree
- The Commands about the Processes
- the latest update validate Binary Search leetcode c++
- Find the second largest element in a Binary Search Tree
- Compute the height of a binary search tree
- 287. Find the Duplicate Number--binary search/快慢指针
- The Opensource about SIP
- About the AOSA
- About the class Crgn
- About the Poem
- oracle 中游标和存储过程的使用
- IOS 动画设计(5)——用缓动函数实现物理动画效果
- 强迫症患者最爱的代码整理功能
- mysql索引总结
- 关于easyui页面表单验证validate
- The termination conditions about the binary search
- Aerospike数据库简介
- 本地mongodb数据库学习
- ProgressBar 漂亮动画
- laravel中MVC的基本用法
- 简析TCP的三次握手与四次挥手
- 一堆友链
- linux shell日志工具类 可以记录日志用
- javascript Date format(js日期格式化)