Have a list of integers like
List<Integer> l = new ArrayList<Integer>();
I think calling l.contains
is slow, how to sort the list. After sorting, will l.contains
behave faster?
Is there any sortedList I can use directly?
Have a list of integers like
List<Integer> l = new ArrayList<Integer>();
I think calling l.contains
is slow, how to sort the list. After sorting, will l.contains
behave faster?
Is there any sortedList I can use directly?
Sorting of list would not make contains operation faster. It still be O(n) in worst case.
However you can sort your list and perform the binary search on top of it.
Collections.sort(l);
Collections.binarySearch(l, a);
This will take O(lg(n)) time in worst case.
But if you want a high performance contains operation consider using HashSet
instead of ArrayList
. It takes nearly constant time.
contains() on a ArrayList doesn't assume the array is sorted, even if it is. You'll want to use some sort of set (HashSet will give you the best find performance, and a LinkedHashSet will retain the order. Even a TreeList will give you better performance.)
TreeSet may be useful for you.
SortedSet<Integer> s = new TreeSet<Integer>(l);
If Collections.sort(l)
does not give the desired result, try Collections.sort(l, comparator)
where "comparator" is something like this:
class MyComparator implements Comparator<Integer>
{
public int compare(Integer lhs, Integer rhs)
{
// perform the desired comparison.
}
}
Edit: I'll leave this up, but the answer by "Mairbek Khadikov" seems to be the best answer.