求两无序不重复数组的交集
//输入:a[]={2, 8,10,4,6,7};b[]={9,3,2,7, 8,5};
//输出:{2,7,8}
[思路]:
1)对两数组进行排序;
2)一次循环判断a和b中元素是否相等,相等则输出;不等则小的值++。
时间复杂度:O(nlogn)
#include "stdafx.h"
#include"iostream"
using namespace std;
//快速排序
//(1)快排之分割
int split(int a[],int left, int right){
int k=a[left];
while(left<right){
while(left<right&&a[right]>=k)
--right;
a[left]=a[right];
while(left<right&&a[left]<=k)
++left;
a[right]=a[left];
}
a[left]=k;
return left;
}
//(2)快排之递归
void quickCurve(int a[], int left,int right){
int SplitPoint=0;
if(left<right){
SplitPoint=split(a, left, right);
quickCurve(a,left,SplitPoint-1);
quickCurve(a,SplitPoint+1,right);
}
}
//(3)快排
void quickSort(int a[], int len) {
quickCurve(a,0,len-1);
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[]={9,3,2,7,8,5};
int b[]={2,8,10,4,6,7};
int m=sizeof(a)/sizeof(a[0]);
int n=sizeof(b)/sizeof(b[0]);
//cout<<m<<endl;
//1)对两数组进行排序;
quickSort(a,m);
/*for(int i=0;i<m;i++)
cout<<a[i]<<" ";
cout<<endl;*/
quickSort(b,n);
/*for(int j=0;j<n;j++)
cout<<b[j]<<" ";
cout<<endl;*/
//2)一次循环判断a和b中元素是否相等,相等则输出;不等则小的值++。
cout<<"无序集合a和集合b的交集是:"<<endl;
if(m<=n){
int i=0;
int j=0;
while(i<m){
if(a[i]==b[j]){
cout<<a[i]<<" ";
++i;
++j;
}
else if(a[i]<b[j])
++i;
else ++j;
} //end while
cout<<endl;
}//end if
return 0;
}
转载地址:http://blog.csdn.net/laoyang360/article/details/8101143