static ArrayList<Integer> furthestAirport(int departingAirport) {
int max = 2, currentSize = 0;
ArrayList<Integer> result = new ArrayList<Integer>();
ArrayList<Integer> tempList = new ArrayList<Integer>();
for (int endKey : stationKeys) {
if (departingAirport != endKey) {
HashSet<ArrayList<Integer>> tempHash = g.shortestPaths(departingAirport, endKey);
if (!tempHash.isEmpty()) {
for (ArrayList temp : tempHash) {
currentSize = temp.size();
if (max <= currentSize) {
max = currentSize;
if (!tempList.contains(endKey))
tempList.add(endKey);
}
}
}
}
}
for (int endKey : tempList) {
if (departingAirport != endKey) {
HashSet<ArrayList<Integer>> tempHash = g.shortestPaths(departingAirport, endKey);
if (!tempHash.isEmpty()) {
for (ArrayList temp : tempHash) {
currentSize = temp.size();
if (max == currentSize) {
if (!result.contains(endKey))
result.add(endKey);
}
}
}
}
}
return result;
}
嗨,有人可以帮我找出我的方法有什么问题吗?旨在找到距离机场最远的距离(顶点)。
它返回一个空数组。 我很感激如果有人能帮助我,因为我孤身一人。
最佳答案
我将稍微扩展我的评论并添加一些代码以使其更清晰:
static List<Integer> furthestAirport(int departingAirport) { //(1)
int max = 2;
Set<Integer> result = new LinkedHashSet<>(); //(2)
for (int endKey : stationKeys) {
if (departingAirport != endKey) {
//(!!)
Set<List<Integer>> tempHash = g.shortestPaths(departingAirport, endKey); //(1)
if (!tempHash.isEmpty()) { // should that ever happen?
for (List<Integer> tempList : tempHash) {
if( tempList.size() > max ) { //(3)
result.clear();
result.add(endKey);
} else if( tempList.size() == max ) { //(4)
result.add(endKey);
}
}
}
}
}
return new ArrayList<>(result);
}
注释:
- (1):使用变量接口(interface)来更改所使用的实现
- (2):使用 LinkedHashSet 可以保持插入顺序并让集合处理重复项(不会添加它们)
- (3):如果当前
tempList
大于当前最大大小,则删除迄今为止可能已收集的任何内容,因为它只能更短。然后添加当前的endKey
,因为它代表“迄今为止”最远的机场。 - (4):如果当前
tempList
与当前最大大小一样长,则只需添加另一个endKey
(这也可以处理任何长度为“第一”的路径2) - (!!):这可能包含错误,可能导致找不到长度至少为 2 的路径
关于java - 返回空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60600464/