gpt4 book ai didi

java - 删除元素的最佳集合

转载 作者:行者123 更新时间:2023-11-30 02:44:47 26 4
gpt4 key购买 nike

在我的程序中,我有一组边,它们必须按重量排序。

在程序的某个地方我必须处理集合,并且每次我都必须删除集合的最大值。

我已经使用了 ArrayList,但我正在寻找更好的解决方案(时间效率):

public class Edge implements Comparable<Edge> {
private int weight;
public void setWeight(int weight) {
this.weight = weight;**
}

@Override
public int compareTo(Edge o) {
return o.weight - this.weight;
}

}

我做了什么:

    private ArrayList<Edge> listOfEdges = new ArrayList<>();
// i suppose here adding some edges in the list

Collections.sort(listOfEdges);
for (int i = 0; i < listOfEdges.size(); i++) {
System.out.println(listOfEdges.get(i).getWeight() + " ");
}

我如何获取并删除列表的最大值。我已经测试了一个treeSet,但边缘可以具有相同的权重,那么接受重复值的完美排序集合是什么。

谢谢

最佳答案

In my program i have a collection of edges ,they have to be ordered by the weight... I have already used an ArrayList but i'm looking for a better solution(time efficiency):

类似二叉树的结构,例如 heap或优先级队列,就是您正在寻找的。一旦指定了对象排序(通过 Comparable 接口(interface)),就可以在 O(1) 时间内获得最大值,并在 O(log n) 时间内删除n 条边。

how can i get&remove the maximum of the list.

peek和pop是队列对象实现的相应方法

关于java - 删除元素的最佳集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40519092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com