Problem: Remove duplicates from a given array of integers.
I want this method to work without using data sets except an array.
My code is currently \$O(n^2 + n) = O(n^2)\$. How do I shorten this? My main goal in writing this code was in the mindset that I am in an interview and that I am given only 20 minutes to solve this problem. Thus, I tried to find the quickest way of solving the problem. Advice on how better to approach these problems would also be very helpful!
public int[] removeDuplicate(int[] arr)
{
int temp[] = new int[arr.length];
boolean[] check = new boolean[arr.length];
int index = 0;
for(int i = 0; i < arr.length; i++)
{
if(check[i] != true)
temp[index++] = arr[i];
else
continue;
int var = arr[i];
for(int j = i+1; j < arr.length; j++)
{
if(var == arr[j])
check[j] = true;
}
}
int returnArray[] = new int[index];
for(int i = 0; i < returnArray.length; i++)
returnArray[i] = temp[i];
return returnArray;
}
add
method ofHashSet
isO(logM)
whereM
is the number of elements in theHashSet
. So using it will give a complexity ofO(N logN)
and notO(N)
– webNeat 8 hours ago