algorithm - A faster way to compare lists for a common element in Java? -


i have graph (implemented vector) of linkedlists , want connect linkedlists not share common elements. think way right takes o(n^3). have loop iterates through vector, nested loop inside iterates through vector (so can compare each list every other one), inside loop use recursion compare lists.

before trying way, tried having while loop inside 2nd loop iterate through each list , use binary search see if 2nd list contains each element, think takes same amount of time or longer. here loop:

 public void addedges(){   for(int =0; < 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));     }    }   }  } 

and here recursion:

 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);   }  } 

assuming i'm reading correctly, can replace compatible method call collections.disjoint static method.

edit: code sample:

public void addedges(){   for(int =0; < size()-1; i++){    for(int j = i+1; j < size(); j++){     if(collections.disjoint(get(i),get(j))){      get(i).linkto(get(j));      get(j).linkto(get(i));     }    }   }  } 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -