How to get 5 highest values from a hashmap?

前端 未结 6 1104
慢半拍i
慢半拍i 2021-02-06 14:49

I have a Hashmap that links a zipcodes stored as keys and population stored as values in a hashmap.

The hashmap contains around 33k entries.

I\'m trying to get t

6条回答
  •  死守一世寂寞
    2021-02-06 15:00

    PriorityQueue would help too, and also a nice topic about how to get top k from a list, you can check this link

    PriorityQueue p = new PriorityQueue(5);
    
    int[] a = new int[]{3,5,10,1,23,42,66,1333,545,110};
    
    for (int i : a){
        p.add(i);
        if (p.size() > 5){
            p.poll();
        }
    }
    
    //output will be highest 5, [42, 66, 110, 1333, 545]
    

    You can have O(n log(k)) time complexity // k is your top value count.

提交回复
热议问题