二分专题1:寻找指定元素(整数查找)
转载 已于 2023-08-15 21:52:08 修改 · 粉丝可见 · 115 阅读 · 0 · 0 · 本内容遵循CC 4.0 BY-SA版权协议 原文链接:https://programmercarl.com/0704.%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE.html · 编辑
文章链接:https://blog.csdn.net/hacker_51/article/details/132297193
题目:

样例1:
cobol<br/>5 3<br/>1 2 3 5 8<br/> |
样例2:
cobol<br/>5 6<br/>1 2 3 5 8<br/> |
解题:
二分法中,需要注意的细节就是
搜索区间的是否合法 即 while() 循环条件的 l 和 r 的控制
左右都是闭区间写法:


代码详解如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| #include <iostream> #define endl '\n' #pragma GCC optimize(3,"Ofast","inline") #define ___G std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0) using namespace std; const int N = 2e6 + 10; int n,m,v[N];
inline int two_Finds() { int l = 0,r = n - 1; while(l <= r) { int mid = l + r >> 1; if(v[mid] > m) r = mid - 1; else if(v[mid] < m) l = mid + 1;
else return mid; } return -1; }
int main() { ___G; cin >> n >> m; for(int i = 0;i < n;++i) cin >> v[i];
cout << two_Finds() << endl;
return 0; }
|
最后提交:

左闭右开区间的写法:


代码详解如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| #include <iostream> #define endl '\n' #pragma GCC optimize(3,"Ofast","inline") #define ___G std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0) using namespace std; const int N = 2e6 + 10; int n,m,v[N];
inline int two_Finds() { int l = 0,r = n;
while(l < r) { int mid = l + r >> 1; if(v[mid] > m) r = mid; else if(v[mid] < m) l = mid + 1;
else return mid; } return -1; }
int main() { ___G; cin >> n >> m; for(int i = 0;i < n;++i) cin >> v[i];
cout << two_Finds() << endl;
return 0; }
|
最后提交:

(PS:参考文献: 《代码随想录》 , 程序员Carl (opens new window) 的原创,此文章只作为个人的学习笔记,仅供交流分享学习经验,绝无恶意抄袭或搬运,更多更详细知识点的学习,关注搜索 程序员Carl 《代码随想录》 ,一起学习,分享经验,共同进步!维护一个良好的技术创作环境!)