您的位置:首页 > 其它

二分查找 变形

2014-05-17 12:59 375 查看
#include<iostream>
using namespace std;

int helper(int a[],int len,int t,bool isleft)
{
if(a == NULL || 0 >= t) return EOF;

int last = EOF;
int left = 0;
int right = len - 1;

while(left <= right)
{
int middle = (left + right)/2;
if(a[middle] > t)
{
right = middle - 1;
}
else if(a[middle]<t)
{
left = middle + 1;
}else{
last = middle;
if(isleft)
right = middle-1;
else
left = middle + 1;
}
}
return last;
}

int main()
{
int a[] = {1,1,2,2,2,2,3,4,5};
int left = helper(a,sizeof(a)/sizeof(a[0]),2,true);
int right = helper(a,sizeof(a)/sizeof(a[0]),2,false);
if(EOF != left && EOF != right)
cout<<left<<" "<<right<<" "<<right-left + 1<<endl;
else
cout<<left<<" "<<right<<" "<<"can not found"<<endl;

}


#include<stdio.h>

int solver(const int a[],const int n,const int t)
{
int total = 0;
if (NULL == a && 0 >= n)
return total;
int start = 0;
int end = n-1;
while(start <= end)
{
printf("%d   %d\n",start,end);
int middle = (start + end)/2;
if(t == a[middle])
{
total = 1;
int cursor = 0;
while(++cursor && middle + cursor < n && t == a[middle + cursor])
total++;
cursor = 0;
while(--cursor && middle + cursor >= 0 && t == a[middle + cursor])
total++;
return total;
}
else if(t > a[middle])
end = middle - 1;
else
start = middle + 1;
}
return total;
}

int main()
{
int a[] = {1,1,1,1,1,1};
int b[] = {1,2,2,2,2,3};
int c[] = {1,2,3,5,6,7};
printf("%d",solver(b,6,4));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: