T183635 二分查找(II)C/C++


在这里插入图片描述

第一种方法,出现一个数记录一下这个数出现的次数,不过在该题测试时有三个测试点时间超限了

#include<iostream>
#include<stdio.h>
using namespace std;


int main()
{
	int n,m;
	cin >> n >> m ;
	int a[n+10],b[200010]={0};
	for(int i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
		//cin >> a[i];
		b[a[i]]++;
	}
	a[n]=200001;

	while(m--)
	{
		int res=0,flag=0;
		int x;
		int i=0;
		scanf("%d",&x);
		//cin >> x ;
		if(b[x]>0)
		{
			while(a[i]<=x&&i<n) 
			{
				if(a[i]!=a[i+1])
					res+=b[a[i]];
				i++;
			}
			printf("%d %d\n",res,res);
			//cout << res << " " << res << endl ;
		}
		else
		{
			while(a[i]<x&&i<n)
			{
				flag=1;
				if(a[i]!=a[i+1])
					res+=b[a[i]];
				i++;
			}
			if(flag&&i<n)
				printf("%d ",res+1);
				//cout << res+1 << " " ;
			else if(a[0]>x) 
				printf("1 ");
				//cout << "1" << " " ;
			else
				printf("NO ") ;
				//cout << "NO" << " " ;
			
			flag=0;
			i=0;
			res=0;
			while(a[i]<x&&i<n)
			{
				flag=1;
				if(a[i]!=a[i+1])
					res+=b[a[i]];
				i++;
			}
			if(flag)
				printf("%d\n",res);
				//cout << res << endl ;
			else 
				printf("NO\n") ;
				//cout << "NO" << endl ;
		}
	} 
}

ACcode:

#include<iostream>
#include<stdio.h>
using namespace std;


int main()
{
	int n,m;
	cin >> n >> m ;
	int a[n+10],b[200010]={0};
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
		//cin >> a[i];
		b[a[i]]=i;
	}
	a[n+1]=200001;

	while(m--)
	{
		int flag=0;
		int x;
		int i=0;
		scanf("%d",&x);
		//cin >> x ;
		if(b[x]>0)
		{
			printf("%d %d\n",b[x],b[x]);
			//cout << res << " " << res << endl ;
		}
		else
		{
			int low = 1, high = n, middle = 0,res=high;
			while(low <= high) {
				middle = (high+low)/2;
				if(a[middle] > x){
					res=middle;
					high = middle-1;
				} 
				else
				{
					low = middle + 1;
				}
			}
			if(a[res] > x) cout << res << " " ;
			else cout << "NO" << " " ;
			
			low = 1;high = n;middle = 0;res=high;
			while(low <= high){
			middle = (high+low)/2;
				if( x > a[middle] ) {
					res=middle;
					low = middle + 1;
				} 
				else
				{
					high = middle-1;
				}
			}
			if (x > a[res] ) cout << res << endl ;
			else cout << "NO" << endl ;
		}
	} 
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值