問題描述
求兩個已排序資料的交集和并集,要求時間複雜度為O(m+n).
解題思路
A數組和B數組,A數組大小為m,B數組大小為n。
1、查找B數組的每個成員是否在A數組中,時間複雜度為O(mn)
2、由于A和B數組都是有序數組,使用二分法查找B數組的每個成員是否在A數組中,時間複雜度為O(n*lgm)。如果n比m大,則查找A數組的成員是否在B數組中,時間複雜度為O(m*lgn)。
3、使用hash表,将A數組的值使用hash表儲存,B中的值判斷是否存在A中,由于hash表的查找時間複雜度為O(1),是以該算法的時間複雜度為O(n)。但是此方法隻适合m比較小的情況,如果A數組比較大,hash表容易産生collision的情況,hash表的查找平均速度将不再是O(1)。
4、使用兩個指針分别指向數組A和數組B,指向資料小的指針往前繼續移動,儲存兩個指針指向相同資料的值,直到兩個指針都指向數組末尾,該算法的時間複雜度為O(m+n)。
交集就是儲存兩個指針指向相同的值,并集就是儲存兩個指針指向不同的值,并且儲存一份指向相同的值
C++代碼
//擷取兩個排序數組的交集
void GetIntersectionSet(int ABuffer[],int ALength, int BBuffer[],int BLength,vector<int>& intersectionSet)
{
int pointerA = ;
int pointerB = ;
while(pointerA < ALength && pointerB < BLength)
{
if(ABuffer[pointerA] < BBuffer[pointerB])
{
pointerA++;
}
else if(BBuffer[pointerB] < ABuffer[pointerA])
{
pointerB++;
}
else
{
intersectionSet.push_back(ABuffer[pointerA]);
pointerA++;
pointerB++;
}
}
}
//擷取兩個排序數組的并集
void GetUnionSet(int ABuffer[],int ALength, int BBuffer[],int BLength,vector<int>& unionSet)
{
int pointerA = ;
int pointerB = ;
while(pointerA < ALength && pointerB < BLength)
{
if(ABuffer[pointerA] < BBuffer[pointerB])
{
unionSet.push_back(ABuffer[pointerA]);
pointerA++;
}
else if(BBuffer[pointerB] < ABuffer[pointerA])
{
unionSet.push_back(BBuffer[pointerB]);
pointerB++;
}
else
{
unionSet.push_back(ABuffer[pointerA]);
pointerA++;
pointerB++;
}
}
if(pointerA < ALength)
{
for(int i = pointerA; i < ALength;i++)
{
unionSet.push_back(ABuffer[i]);
}
}
if(pointerB < BLength)
{
for(int i = pointerB; i < BLength;i++)
{
unionSet.push_back(BBuffer[i]);
}
}
}
測試代碼
int _tmain(int argc, _TCHAR* argv[])
{
//定義排序數組A和B
const int length = ;
int ABuffer[length] = {};
int BBuffer[length] = {};
cout<<"please input orderly A Buffer:"<<endl;
for(int i = ; i < length; i++)
{
cin>>ABuffer[i];
}
cout<<"please input orderly B Buffer:"<<endl;
for(int i = ; i < length; i++)
{
cin>>BBuffer[i];
}
//定義交集集合和并集集合
vector<int> intersectionSet;
intersectionSet.clear();
vector<int> unionSet;
unionSet.clear();
GetIntersectionSet(ABuffer,length,BBuffer,length,intersectionSet);
GetUnionSet(ABuffer,length,BBuffer,length,unionSet);
//輸出交集和并集
cout<<"the intersection set of orderly A and orderly B as follows:"<<endl;
vector<int>::iterator itA;
for(itA = intersectionSet.begin(); itA != intersectionSet.end();itA++)
{
cout<<*itA<<" ";
}
cout<<endl;
cout<<"the union set of orderly A and orderly B as follows:"<<endl;
vector<int>::iterator itB;
for(itB = unionSet.begin(); itB != unionSet.end();itB++)
{
cout<<*itB<<" ";
}
cout<<endl;
return ;
}