Returns the intersection of two unordered and non-repeating arrays.
// Input: a [] = {5, 7, 8, 9, 1, 2, 3}; B [] = {2, 8, 10, 4, 6, 7 };
// Output: {2, 7, 8}
[Idea 1]:
It is output to determine whether the element of element value of array a is in array B.
Time Complexity: O (n2)
[Cpp]
Void cmpInterSection (int a [], int B [], int m, int n)
{
For (int I = 0; I <m; I ++)
{
For (int j = 0; j <n; j ++)
{
If (a [I] = B [j])
{
Cout <a [I] <"\ t ";
Break;
}
} // End for j
} // End for I
Cout <endl;
}
[Idea 2]:
1) sort the two arrays;
2) judge whether the elements in a and B are equal in one loop. If the elements are equal, the output is displayed. If the elements are not equal, the smaller value is ++.
Time Complexity: O (nlogn)
// Fast sorting
[Cpp]
Int divided (int nArr [], int nLeft, int nRight)
{
Int left = nArr [nLeft];
While (nLeft <nRight) // × ¢ Ò â while n »•
{
While (nLeft <nRight & nArr [nRight]> = Linear) // × ¢ Ò â µè ° linear
{
-- NRight;
}
NArr [nLeft] = nArr [nRight];
While (nLeft <nRight & nArr [nLeft] <= unknown) // X ¢ Ò â µè ° unknown
{
++ NLeft;
}
NArr [nRight] = nArr [nLeft];
}
NArr [nLeft] = Beijing;
Return nLeft;
}
// Recursive
Void quickCurve (int nArr [], int nLeft, int nRight)
{
Int nw.tpos = 0;
If (nLeft <nRight)
{
N1_tpos = divided (nArr, nLeft, nRight );
QuickCurve (nArr, nLeft, nPivotPos-1 );
QuickCurve (nArr, nw.tpos + 1, nRight );
}
}
// Fast sorting
Void quickSort (int nArr [], int nLen)
{
QuickCurve (nArr, 0, nLen-1 );
}
Void interSectionOfArray (int a [], int B [], int m, int n)
{
// Fast sorting
QuickSort (a, m );
QuickSort (B, n );
// The intersection is filtered out in a loop.
If (m <n)
{
Int j = 0;
Int I = 0;
While (I <m)
{
If (a [I] = B [j])
{
Cout <a [I] <"\ t ";
I ++;
J ++;
}
Else if (a [I]> B [j])
{
J ++; // small value ++
}
Else
{
I ++; // small value ++
}
}
Cout <endl;
} // End if
}
[Idea 3]:
The hash table stores two arrays in one table, and outputs the elements with a total of 2 counts.
Time Complexity: O (n), a typical space-based time change method.
[Cpp]
Ypedef struct HASHSET
{
Int key; // Value
Int nCnt; // count
} HashSet;
HashSet * pSetArray = new hashSet [m * n]; // space change time
For (int I = 0; I <m * n; I ++)
{
PSetArray [I]. key = 0;
PSetArray [I]. nCnt =-1;
}
// O (n) for output...
Void hashInterSection (hashSet * pSetArray, int a [], int B [], int m, int n)
{
For (int I = 0; I <m; I ++)
{
PSetArray [a [I]. key = a [I];
PSetArray [a [I]. nCnt ++;
}
For (int j = 0; j <n; j ++)
{
PSetArray [B [j]. key = B [j];
PSetArray [B [j]. nCnt ++;
}
For (int k = 0; k <m * n; k ++)
{
If (pSetArray [k]. nCnt = 1)
{
Cout <pSetArray [k]. key <"\ t"; // accumulate twice-1 + 1 + 1 = 1.
}
}
Cout <endl;
}
Or do you have any better methods? Welcome to discuss them. Thank you!