原题目在这里:http://ac.jobdu.com/problem.php?cid=1039&pid=20
解题思路比较简单:
1) 因为数组已经排序, 所以直接使用 binary search查找目标数字。 若这个目标数字在数组中存在,就返回它的索引,此时 Count =1。
2)从这个索引的位置,前向遍历该数组直到到达数组的下界或当前的元素 不等于目标数字, 当然在这个遍历的过程中要记录下目标元素的重复次数:a。然后从这个索引位置后向遍历数组直到到达数组的上界界或当前的元素 不等于目标数字遍历的过程中要记录下目标元素的重复次数:b 。
3) Count = 1+a +b.
#include<stdio.h>
int Input[1000001];
int T[1000];
// return 0, indicate the number is not exist
// else the return value is index in the array
int SearchNumber(int*A, int Target, int p, int r)
{
if(p<=r)
{
if( A[(p+r)/2] == Target )
{
return (p+r)/2;
}
else if( A[(p+r)/2] < Target)
{
return SearchNumber(A, Target, (p+r)/2 +1, r);
}
else
{
return SearchNumber(A,Target, p, (p+r)/2 -1);
}
}
return 0;
}
int QueryCount(int*A, int Target, int start, int end)
{
int index = 0;
int Count = 0;;
int t = 0;
index = SearchNumber(A,Target, start, end);
if(index == 0 ) return 0;
++Count;
t = index-1;
while(t>= start && A[t] == Target)
{
++Count;
--t;
}
t = index + 1;
while(t<=end && A[t] == Target)
{
++Count;
++t;
}
return Count;
}
int CountOccurance()
{
int Size = 0;
int TCount = 0;
int index = 0;
int OccuranceCount = 0;
while(scanf("%d",&Size) == 1)
{
for(index = 1; index<=Size;++index)
{
scanf("%d",&Input[index]);
}
scanf("%d", &TCount);
for(index = 0; index<TCount; ++index)
{
scanf("%d",&T[index]);
OccuranceCount = QueryCount(Input,T[index],1,Size);
printf("%d\n",OccuranceCount);
}
}
return 0;
}
int main()
{
CountOccurance();
return 0;
}