As a part of the Java interview question paper I have got following issue to solve. But I am bit wonder whether how can I implement it without any Collection or intermediate
This is the simplest solution I can think of. I just added an extra counter so that integers with two or more repetitions still in the array are ignored.
static int findNumber(int[] arr)
{
int duplicateCounter = 0;
System.out.print("Duplicates: ");
for(int i = 0; i < arr.length; i++)
{
boolean duplicate = false;
int numOfOccurrences = 1;
for (int j = (i+1); j < arr.length; j++)
{
if (arr[i] == arr[j])
{
numOfOccurrences++;
duplicate = true;
}
}
if(numOfOccurrences == 2 && duplicate == true)
{
duplicateCounter++;
System.out.print(arr[i] + " ");
}
}
return duplicateCounter;
}
My test run: Test run
Input: 1, 2, 3, 4, 2, 4, 1, 1, 1
Duplicates: 2 4 1
Number of duplicates: 3