如何在Java中使用允许重复的TreeSet? [英] How do I use a TreeSet in Java that allows Duplicates?
问题描述
我想要一个具有O(logn)时间优先队列功能的数据结构,并且还能够删除某个特定元素,而该元素不一定是O(logn)时间的开头。我听说Java中的TreeSet可以这样做,但不允许重复,如何解决呢?
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?
推荐答案
使用 TreeMap ,允许插入在 log n
的时间内删除,并在 log n
的时间内删除。您可以在那里 TreeMap< Integer,Integer>
,其中key存储元素的值,value存储元素的频率。
Use TreeMap which allows insertion in log n
time and deletion in log n
time. You can have there TreeMap<Integer,Integer>
where key stores the value of element and value stores the frequency of the element.
如果只需要执行 Insert
和 Delete
操作,请使用Java的 优先级队列 。它还允许使用堆插入
存储数据。 log n
时间并删除 log n
时间
If you need to do only Insert
and Delete
operation , Use Java's Priority Queue. It also allows insertion in log n
time and deletion in log n
time as it uses Heaps
to store the data.
您可以执行 Insertion
, TreeMap
的功能>删除。
You can do Insertion
, Deletion
by implementing the functions for TreeMap
.
TreeMap<Integer,Integer> map=new TreeMap<Integer,Integer>();
插入:
public boolean insert(int value) throws Exception
{
try
{
if(!map.containsKey(value))
map.put(value,0);
map.put(value,map.get(value)+1);
return true;
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
}
队列头(偷看):
public int getHead()
{
if(map.firstKey()==null)
return null;
return (int)map.firstKey();
}
移出并取回头部(民意测验):
public int removeHead()
{
if(getHead()==null)
return null;
int head=getHead();
if(map.get(head)==1)
map.remove(head);
else
map.put(head,map.get(head)-1);
}
这篇关于如何在Java中使用允许重复的TreeSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!