For example, the following question states:
Write a method which takes two array of integers as parameter and prints all their common elements.
My attempt:
public static void commonElements(int[] A, int[] B)
{
for(int i = 0; i < A.length; i++)
for(int j = 0; j < B.length; j++)
if(A[i] == B[j])
System.out.print(A[i] + " ");
}
Now, the problem is that this code works only if the elements in each array occurs only once. But for example if in array A there were two 4s and in array B there were four 4s, the output would be eight 4s, which is wrong!
So, how can I check if a certain element in an array has already occured so that the code won't take it in account.