I wanted to 'remove' elements in ArrayList by creating a new ArrayList that contains all elements except the duplicates. Duplicates are selected by an comparator and the ordering should be maintained. The algorithm is just iterating over the ArrayList and adding each element that isn't already in the new list. The work is done in a method that is going through the entire ArrayList and checking for equality. Here is the code:
public static <T> ArrayList<T> noDups(Comparator<T> cmp, ArrayList<T> l) {
ArrayList<T> noDups = new ArrayList<T>();
for(T o : l) {
if(!isIn(cmp, o, l))
noDups.add(o);
}
return noDups;
}
public static <T> boolean isIn(Comparator<T> cmp, T o, ArrayList<T> l) {
Iterator<T> i = l.iterator();
if (o==null) {
while (i.hasNext())
if (i.next()==null)
return true;
} else {
while (!(i.hasNext()))
if (o.equals(i.next()))
return true;
}
return false;
}
I'm curious about the time complexity this algorithm has. My thoughts are: For the first step there is no work, because the ArrayList noDups is empty. For the second step there is one check, for the third 3 and so on to n-1. So we have 1+2+...+n-1. Is that correct and what time complexity would that be?