I have to write code to fill an array of size n with unique random numbers in the range 0-10n
(inclusive). I can do it with O(n^2)
complexity but I need to do it with O(n)
complexity. I can't think of a way to do it that doesn't involve generating the random number, then going back through the partly filled array to check whether there are duplicates in the array.
For reference, here's my O(n^2)
version of the method:
private static void fillWithUniqueN2(int[] numbers)
{
Random rng = new Random();
for (int i = 0; i < numbers.length; i++)
{
boolean added = false;
while (!added)
{
int newNumber = rng.nextInt(numbers.length);
boolean unique = true;
for (int j = 0; j < i; j++)
{
if (newNumber == numbers[j])
{
unique = false;
}
}
if (unique)
{
numbers[i] = newNumber;
added = true;
}
}
}
}