Reputation: 1463
Im doing a Java application and Im facing some doubts in which concerns performance.
I have a PriorityQueue which guarantees me the element removed is the one with greater priority. That PriorityQueue has instances of class Event (which implements Comparable interface). Each Event is associated with a Entity.
The size of that priorityqueue could be huge and very frequently I will have to remove events associated to an entity.
Right now Im using an iterator to run all the priorityqueue. However Im finding it heavy and I wonder if there are better alternatives to search and remove events associated with an entity "xpto".
Any suggestions?
Thanks!
Upvotes: 3
Views: 414
Reputation: 23265
It sounds like you need to implement a souped-up priority queue. In particular, you need O(logN) removal time. You can do this by keeping two data structures, an array of Events which is basically the binary heap storing your priority queue, and a HashMap from Event to the offset of that Event in the array (or maybe from Entity to a list of offsets of Events in that array).
You can then do normal heap operations as you would for a priority queue, you just need to update the hash map mappings every time an Event is moved. To remove an Event, look up the index of that event in the hash table and do a remove operation on the heap starting at that index.
Upvotes: 0
Reputation: 2678
A couple of ideas:
Upvotes: 1
Reputation: 297195
I'd suggest you make a class composed of a PriorityQueue and a Set, with the following operations:
Upvotes: 0
Reputation: 41180
Since remove
is a linear time operation, you are getting O(N*N) performance.
If you subclass PriorityQueue
and create a new method (named removeIf
perhaps) that combines the iterator and remove
methods then you could reduce this to O(N log(N)).
Upvotes: 0
Reputation: 8757
Theres a few options:
Upvotes: 1