I was asked to write my own implementation to remove duplicated values in an array. Here is what I have created. But after tests with 1,000,000 elements it took very long time to finish. Is there something that I can do to improve my algorithm or any bugs to remove ?
I need to write my own implementation - not to use Set
, HashSet
etc. Or any other tools such as iterators. Simply an array to remove duplicates.
public static int[] removeDuplicates(int[] arr) { int end = arr.length; for (int i = 0; i < end; i++) { for (int j = i + 1; j < end; j++) { if (arr[i] == arr[j]) { int shiftLeft = j; for (int k = j+1; k < end; k++, shiftLeft++) { arr[shiftLeft] = arr[k]; } end--; j--; } } } int[] whitelist = new int[end]; for(int i = 0; i < end; i++){ whitelist[i] = arr[i]; } return whitelist; }
We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.
If you are allowed to use Java 8 streams:
Arrays.stream(arr).distinct().toArray();
you can take the help of Set collection
int end = arr.length; Set<Integer> set = new HashSet<Integer>(); for(int i = 0; i < end; i++){ set.add(arr[i]); }
now if you will iterate through this set, it will contain only unique values. Iterating code is like this :
Iterator it = set.iterator(); while(it.hasNext()) { System.out.println(it.next()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With