I want a data structure with priority queue functions in O(logn) time and also be able to delete a specific element that's not necessarily the head in O(logn) time. I heard the TreeSet in java does it but does not allow Duplicates, How do i get around this?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Use TreeMap which allows insertion in
log n
time and deletion inlog n
time. You can have thereTreeMap<Integer,Integer>
where key stores the value of element and value stores the frequency of the element.If you need to do only
Insert
andDelete
operation , Use Java's Priority Queue. It also allows insertion inlog n
time and deletion inlog n
time as it usesHeaps
to store the data.You can do
Insertion
,Deletion
by implementing the functions forTreeMap
.Insertion :
Head of the queue(peek) :
Remove and retrieve head(poll) :
I don't have enough reputation to comment so i'll say this here. I think that removing an element in a priorityqueue is O(N) as stated here.
You might be able to get around this in some cases. If you don't plan on adding an object after removing it, you could make a wrapper around the priorityqueue and keep a hashSet of removed elements. Then, if you come across that object when polling, you discard it.
You could also create your own priorityqueue using an ordered list. You could then use a binary search to find insert positions or the index to remove efficiently.