G - 二分法+时间复杂度(简单)

本文介绍了一种使用快速排序和二分法解决蒜头君查询长度为nn数组中整数问题的编程技巧。通过先对数组进行排序,然后采用二分查找的方式,提高了查询效率。展示了如何在C语言中实现这一过程,并给出了样例输入和输出。
摘要由CSDN通过智能技术生成

蒜头君手上有个长度为 nn 的数组 AA。由于数组实在太大了,所以蒜头君也不知道数组里面有什么数字,所以蒜头君会经常询问整数 xx 是否在数组 AA 中。

输入格式

第一行输入两个整数 nn 和 mm,分别表示数组的长度和查询的次数。

接下来一行有 nn 个整数 a_iai​。

接下来 mm 行,每行有 11 个整数 xx,表示蒜头君询问的整数。

输出格式

对于每次查询,如果可以找到,输出"YES",否则输出"NO"

数据范围

1 \le n, m \le 10^5, 0 \le x \le 10^61≤n,m≤105,0≤x≤106。

Sample Input

10 5
1 1 1 2 3 5 5 7 8 9
0
1
4
9
10

Sample Output

NO
YES
NO
YES
NO

这道题需要使用二分法,先排序,再二分,固代码如下

#include <stdio.h>
void quicksort(int left,int right,int str[])            //快速排序
{
	int i,j,temp,t;
	if(left>right)
		return;
	temp=str[left];
	i=left;
	j=right;
	while(i!=j)
	{
		while(str[j]>=temp&&j>i)
		{
			j--;
		}
		while(str[i]<=temp&&j>i)
		{
			i++;
		}
		if(i<j)
		{
			t=str[i];
			str[i]=str[j];
			str[j]=t;
		} 
	}
	str[left]=str[i];
	str[i]=temp;
	quicksort(left,i-1,str);
	quicksort(i+1,right,str);
	return;
}
int Bin_Search(int *str,int cnt, int target)            //二分法
{
	int first=1,last=cnt,mid;
	while(first<=last)
	{
		mid=(first+last)/2;
		if(str[mid]>target)
		{
			last=mid-1;
		}
		else if(str[mid]<target)
		{
			first=mid+1;
		}
		else
			return 1;
	}
	return 0;
}
 
int main(void)
{
	int n,m,i,j,flag;
	scanf("%d%d",&n,&m);
	int str[n];
	for(i=1;i<=n;i++)
	{
		scanf("%d",&str[i]);
	}
	quicksort(1,n,str);
	while(m--)
	{
		scanf("%d",&j);
		flag=Bin_Search(str,n,j);
		if(flag==1) printf("YES\n");
		else printf("NO\n");
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值