A,B两个整数集合,设计一个算法求他们的交集,尽可能的高效(牛客网)

#include<iostream>
using namespace std;
/*
1)先使用快速排序,使得两个数组有序;
2)然后利用二分查找的方法,在数组B中查找;
3)其中,注意在数组B中,使用二分查找的起点,是根据上次查找的结果开确定的;这样可以进一步提高速度;
*/
int Sort(int array[],int low,int high)
{
	int temp=array[low];
	int pos=low;
	while(low<high)
	{
		while(array[high]>temp && high>low)high--;
		if(high>low)array[low]=array[high];
		while(array[low]<temp && high>low)low++;
		if(low<high)array[high]=array[low];
	}
	array[low]=temp;
	return low;
}
void QuickSort(int array[],int low,int high,int len)
{
    if(low<high)
	{
		int mid=Sort(array,low,high);
		QuickSort(array,low,mid-1,len);
		QuickSort(array,mid+1,high,len);
	}
}

int BinarySearch(int array[],int len,int start,int key)
{
	int pos=-1;
	int low=start;
	int high=len-1;
    int mid=0;
    while(low<=high)
	{
		mid=(low+high)/2;
		if(key>array[mid])low=mid+1;
		else if(key<array[mid])high=mid-1;
		else if(key==array[mid]) {pos=mid;break;}
	}
	return pos;
}
void Output(int array_A[],int array_B[],int len_A,int len_B)
{
	QuickSort(array_A,0,len_A-1,len_A);
    QuickSort(array_B,0,len_B-1,len_B);
	int i=0,j=0,current=0;//current 记录当前查找的位置;
	int*array_C =new int [len_A];
	int count=0;
	for(i=0;i<len_A;i++)
	{
		j=BinarySearch(array_B,len_B,current,array_A[i]);
		if(j==-1){continue;}
		else{
			array_C[count]=array_A[i];
			count++;
			current=j+1;
		}
	}
	if(array_C!=NULL)
	{
		for(i=0;i<count;i++)
		{
			cout<<array_C[i]<<" ";
		}
		cout<<endl;
	}
	delete []array_C;
	array_C=NULL;
}

int main()
{
	int array_A[10]={5,1,7,3,9,0,45,8,12,11};
	int array_B[10]={15,1,17,3,23,0,45,33,12,11};
	int len_A=10;
	int len_B=10;
    Output(array_A,array_B,len_A,len_B);
	return 0;
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值