my understanding of (lower bound,upper bound) binary search, in C++, thanks to two post
2015-08-01 14:35
561 查看
If you understand the comments below, never will you make mistakes with binary search!
thanks to A simple CPP solution with lower_bound
and C++ O(logn) Binary Search that handles duplicate, thanks to phu1ku ‘s answer on the second post.
http://en.cppreference.com/w/cpp/algorithm/upper_bound
Returns an iterator pointing to the first element in the range [first, last) that is greater than value.
http://en.cppreference.com/w/cpp/algorithm/lower_bound
Returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value.
If want to practice, code on your own, try https://leetcode.com/problems/search-insert-position/ , https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ , https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ and https://leetcode.com/problems/search-a-2d-matrix-ii/ , and see the discusses.
thanks to A simple CPP solution with lower_bound
and C++ O(logn) Binary Search that handles duplicate, thanks to phu1ku ‘s answer on the second post.
http://en.cppreference.com/w/cpp/algorithm/upper_bound
Returns an iterator pointing to the first element in the range [first, last) that is greater than value.
http://en.cppreference.com/w/cpp/algorithm/lower_bound
Returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value.
If want to practice, code on your own, try https://leetcode.com/problems/search-insert-position/ , https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ , https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ and https://leetcode.com/problems/search-a-2d-matrix-ii/ , and see the discusses.
[code]int binarySearch(vector<int>& nums, int target) { /// return index of first one that comp(item,target)==true, or nums.size() if not found /// comp is greater or equal to for lower_bound /// comp is greater for upper_bound int first=0, last=nums.size(), mid; while (first<last) { mid=first+((last-first)>>1); // first<=mid, mid<last /// if comp(item,target)==false, advance first // if(nums[mid]<=target) // for upper_bound if (nums[mid]<target) // for lower_bound first=mid+1; // first always increases else /// else recede last last=mid; // last always decreases (even last-first==1) } return first; }
相关文章推荐
- C语言的那些秘密之---函数返回局部变量
- C语言:循环单链表的创建,遍历,插入
- C++ 输入输出总结
- sizeof(struct)分析(包括union)
- c语言中break和continue的用法和区别
- 在C语言中 switch语句的用法
- ok6410 AD C++ dll制作并在C#中调用
- 关于C++字符串读取
- C++ 管道
- C++ 管道
- C++/CLI学习笔记1—新的托管类型
- c++builder 将Handle句柄转成对象
- ROS学习<四> 发布与订阅,服务与客户(C++)
- C51语法
- C++ 全局变量和局部变量
- 浅谈C++中指针和引用的区别
- c/c++笔试题目
- C++ Opencv播放AVI
- c++带默认参数的函数的声明、定义及使用总结
- C/C++编译器GCC下的常用编译命令总结