数字在排序数组中出现的次数

题目描述:

统计一个数字在排序数组中出现的次数。

poj 网址:http://ac.jobdu.com/problem.php?pid=1349

可以AC的代码,看主要函数就行了,该poj系统的输入输出做的太烂,我用cin不支持,老报超时的错误

 

int findFirstPos(int *arr,int target,int start,int end, int len)
{
    while(start<end)
    {
        int mid=(end-start)/2+start;
        if(arr[mid]==target)
        {
            if(mid==0 || (mid>0 && arr[mid-1]!=target))
            {
                return mid;
            }else
            {
                end=mid-1;
            }
        }else if(arr[mid]>target)
        {
            end=mid-1;
        }else
        {
            start=mid+1;
        }
    }
    if(arr[start]==target)
    {
        return start;
    }else
    {
        return -1;
    }

}
int findLastPos(int *arr, int target,int start, int end,int len)
{
    while(start<end)
    {
        int mid=(end-start)/2+start;
        if(arr[mid]==target)
        {
            if(mid==len-1 || (mid<len-1 && arr[mid+1]!=target))
            {
                return mid;
            }else
            {
                start=mid+1;
            }
        }else if(arr[mid]>target)
        {
            end=mid-1;
        }else
        {
            start=mid+1;
        }
    }
    if(arr[start]==target)
    {
        return start;
    }else
    {
        return -1;
    }
}
int timesForSequence(int *arr,int target,int start,int end,int len)
{
    int firstPos=findFirstPos(arr,target,start,end,len);
    int lastPos=findLastPos(arr,target, start, end,len);
    if(firstPos!=-1 && lastPos!=-1)
    {
        return lastPos-firstPos+1;
    }
    return 0;
}

int n,m,k,a[1000000];
inline void read(int &data) 
{ 
	char ch = getchar(); 
while (ch < '0' || ch > '9') 
	ch = getchar(); 
     data = 0; 
do{  
	data = data*10 + ch-'0'; 
	ch = getchar(); 
}while (ch >= '0' && ch <= '9');
} 
int main(int argc, const char * argv[])
{
	while(scanf("%d",&n)!=EOF)    
	{
		for(int i=0;i<n;i++)
		{
			read(a[i]);  
		}
		read(m);       
		for(int j=0;j<m;j++)
		{
			read(k);            
			cout<<timesForSequence(a,k,0,n-1,n)<<endl;
		}
	}

	return 0;
}


 

 

posted on 2013-07-31 21:12  you Richer  阅读(240)  评论(0编辑  收藏  举报