Let me start by saying that checking for identity of double
s is not a good practice. For more details see: What every programmer should know about floating points.
You should use more robust double
comparisons.
Now, that we are done with that, let's face your problem.
You are dealing with variation of Element Distinctness Problem with floating points number.
Generally speaking, under the algebraic tree computation model, one cannot do it better than Omega(nlogn)
(references in this thread: https://stackoverflow.com/a/7055544/572670).
However, if you are going to stick with the double
s identity checks (please don't), you can use a stronger model and hash table to achieve O(n)
solution, by maintaining a hash-table based histogram (implemented as HashMap<Double,Integer>
) of the elements, and when you are done, scan the histogram and yield the key of the highest value.
(Please don't do it)
There is a complex way to do achieve O(n)
time based on hashing, even when dealing with floating points. This is based on adding elements to multiple entries of the hash table and assuming a hash function is taking a range of elements [x-delta/2,x+delta/2)
to the same hash value (so it is hashing in chunks [x1,x2)->h1, [x2,x3)->h2, [x3,x4)->h3, ....
) . You then can create a hash table where an element x
will be hashed to 3 values: x-3/4delta, x, x + 3/4delta
.
This guarantees when checking an equal value later, it will have a match in at least one of the 3 places you put the element.
This is significantly more complex to implement, but it should work. A variant of this can be found in cracking the code interview, mathematical, question 6. (Just make sure you look at edition 5, the answer in edition 4 is wrong and was fixed in the newer edition)
As another side note, you don't need to implement your own sort. Use Arrays.sort()