Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most Efficient Mode Function In Java

Tags:

java

mode

I have a huge int array which I need to find the Mode of,

Ive seen a few methods that use 2 for loops (one nested) which seems unnecessary.

The only way I can think to find the mode with only one loop involves using Maps:

int[] elements = new int[]{....numbers...};
Map<Integer,Integer> map = new .....Map Type....;
for(int number : elements){
    if(map.containsKey(Integer.valueOf(number))){
        map.put(Integer.valueOf(number),map.get(Integer.valueOf(number))+1);
    }else{
        map.put(Integer.valueOf(number),1);
    }
}

Im not sure what kind of speed benefits using maps would actually give. Is there a better method?

like image 246
Eduardo Avatar asked Apr 16 '26 00:04

Eduardo


1 Answers

If you use a hash map, the runtime complexity of your algorithm should be O(n): You visit each of the n elements once, and HashMap lookup and write is usually assumed to be O(1). So in total you get O(n * 1) which is O(n). If you use a tree map, you get O(n log n).

Compared to two nested loops (which sounds like O(n²)), the speed improvement is going from quadratic to linear, which is quite good: For 1000 elements, you perform 1000 "steps" instead of 1,000,000.

P.S. Getting better than linear is probably hard here -- can't imagine a way of calculating this without visiting each element at least once.

like image 91
Stefan Haustein Avatar answered Apr 18 '26 14:04

Stefan Haustein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!