How we could find max non-repeatable value in the array with a time ~O(N)
I was trying to do it during huge time, but I found only ~O(2N):
int solution(int[] A) {
List<Integer> arr = new ArrayList<Integer>();
Set<Integer> set = new HashSet<Integer>();
int max = 0;
for(int i = 0; i < A.length; i++) {
if(!set.add(A[i])) arr.add(A[i]);
}
for(int i = 0; i < A.length; i++) {
if (max < A[i] && !arr.contains(A[i])) max = A[i];
}
return max;
}
Could we do it a little bit faster?!
The idea is to count the number of occurrence, and store it in a treeMap. since treeMap is sorted, we can find the last (biggest) number that is not repeated (value of 1)
You could probably sort your array in descending order using the Radix sort and then loop over it and check wheter
currentIndex == currentIndex + 1
.This will give you a maximum complexity of
O(n*x)
which is basically the same asO(n)
if I'm not mistaking and still better than the actualO(n^2)
you're usingHere you map each number to a number of times it present in the array.
In this case complexity is O(n).
And just out of integer possible the fastest implementation possible