bool hasDuplicate = false;
int[] a = new int[] {1, 2, 3, 4};
int[] b = new int[] { 5, 6, 1, 2, 7, 8 };
I need compare all elements of array A with element of array B and in case of a duplicate element in B, set hasDuplicate on TRUE.
bool hasDuplicate = false;
int[] a = new int[] {1, 2, 3, 4};
int[] b = new int[] { 5, 6, 1, 2, 7, 8 };
I need compare all elements of array A with element of array B and in case of a duplicate element in B, set hasDuplicate on TRUE.
To efficiently compare all elements in one set to another, you can make a
HashSet
of one of them. Also, you can exit out of the loop as soon as you find the first match:This is an O(n+m) solution, compared to having two nested loops comparing all values which is an O(n*m) solution.
You should sort your data, O(nlog n) and then you could simply do a one pass through each of them, O(n), where you increment the lowest of them. Be aware of data with same number twice, e.g:
a = {1 3 3 5 8}
b = {2 3 5 5 8}
I did it with
for
loop. The point is that we compare each member to members from arrayb
. Soa[0]
is compared to every member in the arrayb
first and then it goes toa[1]
and does the same thing, and so on, until it finds a match.Why don't we try to use LINQ? Check out the following code,
I know you don't want a one line solution but I'll leave my answer for other users who might want a simple solution for the same problem.
If you don't want to use
Linq
, you could use SequenceEqual.bool equal = Array1.SequenceEqual(Array2);
Hope it helps.