二分查找模板和详细练习题
Posted Mr_渣渣辉
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分查找模板和详细练习题相关的知识,希望对你有一定的参考价值。
二分查找练习题:
查找
二分查找
Doubles
Pie
Can you solve this equation?
Can you find it?
Wildcard
4 Values whose Sum is 0
Median
二分查找基础模板
int binarySearch(int a[],int ans,int length)
int left = 1 , right = length - 1;
while(left <= right)
int middle = left + (right - left) / 2;
if(a[middle] == ans)
return middle;
else if(a[middle]>ans)
right = middle - 1;
else
left = middle + 1;
return -1;
左边界二分模板
int binarySearch(int a[],int ans,int length)
int left = 1 , right = length ;
while(left < right)
int middle = left + (right - left) / 2;
if(a[middle] == ans)
right = middle;
else if(a[middle]>ans)
right = middle ;
else
left = middle + 1;
return a[left] == ans ? left : -1;
右边界二分模板
int binarySearch(int a[],int ans,int length)
int left = 1 , right = length+1 ;
while(left < right)
int middle = left + (right - left) / 2;
if(a[middle] == ans)
left = middle + 1;
else if(a[middle]>ans)
right = middle ;
else
left = middle + 1;
return a[left -1] == ans ? left - 1 : -1;
以上是关于二分查找模板和详细练习题的主要内容,如果未能解决你的问题,请参考以下文章