我有LinkedLists的图形(用矢量实现),我想连接不共享任何公共元素的LinkedLists。我认为我现在这样做的方式需要O(n^3)。我有一个for循环遍历Vector,然后嵌套for循环遍历Vector(以便我可以将每个List与其他每个List进行比较),然后在循环内部使用递归来比较列表。比较Java中常见元素的列表的更快方法?
在尝试这种方法之前,我尝试了在第二个for循环中循环遍历每个列表并使用二进制搜索来查看第二个列表是否包含每个元素,但我认为这需要相同数量的时间或更长。 这里是我的循环:
public void addEdges(){
for(int i =0; i < size()-1; i++){
for(int j = i+1; j < size(); j++){
if(compatible(get(i),get(j),1,1)){
get(i).linkTo(get(j));
get(j).linkTo(get(i));
}
}
}
}
,这里是我的递归:
public boolean compatible(Row a, Row b, int indexA, int indexB){
if(a.get(indexA).getEnd() == b.get(indexB).getEnd()){
return false;
}
else if(a.get(indexA).getEnd() == 0){
return true;
}
else if(a.get(indexA).getEnd() > b.get(indexB).getEnd()){
return compatible(a,b,indexA+1,indexB);
}
else{
return compatible(b,a,indexB+1,indexA);
}
}
不错,使代码更简单,但他的'compatible'方法似乎是依赖于关于数据结构的假设,所以它应该比默认方法更有效。 – 2010-11-16 18:26:55
@迈克尔:我想到了这一点,但我想我应该发布这种方式,以防万一它真的做他想做的事情。 – Powerlord 2010-11-16 18:31:07
@Michael:这里的困惑是我不确定'get(i)'和'get(j)'返回了什么。尽管'compatible'方法采用了'Row'对象,我假定'LinkedList'。 – Powerlord 2010-11-16 18:34:51