Map and min-heap for better speed
Can a map and a min-heap used together give better amortized time that either on their own?
Let's suppose I have a project where I need to track several items. These items have an expiration time and a unique id:
class Item {
ID uid;
Time expiration;
};
For this example, both Time and ID are primitive integral data types. I need to be able to quickly access an item by id, and I also need to be able to find the minimum expiration of all items.
Additionally, I will make numerous insertions and deletions.
Using a map, I will get amortized look up times of O(log n). (Yes, I'll provide a compare function for that.) But finding the min value is O(n).
If I use a min-heap, my look up time by id will be O(n), but finding the min expiration is O(1).
In both cases, insertion are O(log n). For this program, deletions will only occur for the minimum item.
Or, I could use both. A map and a min-heap that track the same objects.
Given this set up, would it be beneficial to use both a m开发者_如何学运维in-heap and a map to avoid O(n) complexity?
Yes, using double indexes will probably help you (given a sufficient number of items to defeat the constant factors involved). However, be careful - you'll want to keep track of where your item is in the min-heap so you can delete it from the heap quickly.
精彩评论