将元素添加到根据其成本递增自动正确的位置,并获得最佳性能
我之前有一个问题: 如何根据两个参数对对象列表进行排序以在 Java 中进行比较?
现在我想要这样做:
我将定义一个列表,当我添加 en 元素时,它将找到根据其成本正确放置它。 (我不想生成一个包含无序元素的列表,然后对它们进行排序)
我想以最高的性能来做到这一点。我的意思是我的列表每次都会被排序,所以当我想在该列表中添加一个元素时,它将添加到有序列表中。有序列表的成本可能是 O(logn),通过二分搜索找到正确的位置(即使找到位置可能成本更低,向该列表(即 ArrayList)添加元素可能需要比其好处更多的成本,因此您可以建议添加如果您认为使用该类(ArrayList 等)不擅长 total)
I had a question previously: How to sort a list of objects according to two parameters to compare at Java?
Now I want to do that:
I will define a list and when I add en element it it will find the correct place for it according the its cost. (I don't want to generate a list that has unordered elements and sort them after that)
I want to do that with most performance. I mean my list will be ordered everytime so when I want to add an element o that list it will be an adding to an ordered list. Cost of ordered list may be O(logn) with finding the correct place with binary search(even finding the place maybe with less cost, adding element to that list(i.e. an ArrayList) may require more cost than its benefits so you can suggest adding element without binary search implementation if you think that using that class(ArrayList, etc. etc.) is not good at total)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 TreeSet(首先插入 O(log n),然后删除 O(1))或 PriorityQueue(先插入 O(1),然后删除 O(log n))
注意:TreeSet 在插入时排序,PriorityQueue 是不是。
避免 O(log n) 操作的唯一方法是对可能值的范围做出一些严格的假设,但这在这里不太可能有帮助。
You can use TreeSet (which O(log n) insert and O(1) remove first) or PriorityQueue (which is O(1) insert and O(log n) remove first)
Note: TreeSet is sorted as you insert, PriorityQueue is not.
The only way to avoid an O(log n) operation is to make some strict assumptions about the range of possible values which unlikely to be helpful here.