How can I compare the O
complexity of these two methods?
Here is the first method:
protected static List<Integer> removeDuplicates1(List<Integer> source) {
List<Integer> tmp = new ArrayList<Integer>();
for (Integer element : source) {
if (!tmp.contains(element)) {
tmp.add(element);
}
}
//Collections.sort(tmp);
return tmp;
}
And the second one:
protected static List<Integer> removeDuplicates2(List<Integer> source) {
return new ArrayList<Integer>(new HashSet<Integer>(source));
}
UPD
I don't know how to calculate the O complexity of both methods.
UPD2
Ok, the time complexity of the first method is O(n^2)
, the second is O(n)
. And what about memory usage? Who is more greedy and why?
The second is better
O(n)
complexity (O(n^2)
for the first).For the first you go through the list in the loop (
n
) and for each operation runcontains()
which in turn goes through the tmp list to find whether the element is there (one moren
).For the second method operations of adding in the
Set
is constant so in fact just onen
.