2012-01-16 47 views
3

有像我有一个整数列表,如何排序?

List<Integer> l = new ArrayList<Integer>(); 

我想打电话l.contains很慢,如何使列表排序整数列表。排序后,l.contains会更快吗?

是否有任何sortedList我可以直接使用?

+2

'l.sort()'不起作用? http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#sort%28java.util.List%29 – Oliver 2012-01-16 15:08:12

+3

@Oliver'sort'没有在'Collection'上定义 – adarshr 2012-01-16 15:09:14

+0

你可能会发现这也有用也http://stackoverflow.com/questions/2661065/a-good-sorted-list-for-java – Marthin 2012-01-16 15:10:41

回答

13

它不能变得比这更简单。

Collections.sort(l); 
4

您可以使用Collections.sort(l);

1

包括()上的ArrayList不承担数组进行排序,即使它是。你要使用某种集合(HashSet的会给你最好的发现性能和LinkedHashSet将保留顺序。即使是的TreeList会给你更好的性能。)

0

TreeSet可能对您有用。

SortedSet<Integer> s = new TreeSet<Integer>(l); 
+0

请注意,这也会删除重复项,这可能不是user705414想要的。 – Jesper 2012-01-16 15:30:35

+0

是的,你说得对,但问题的主要目的是让** l.contains **更快执行。 – 2012-01-16 15:37:56

7

排序列表不会使包含操作更快。在最坏的情况下它仍然是O(n)。

但是,您可以对列表进行排序并在其上执行二进制搜索。

Collections.sort(l); 
Collections.binarySearch(l, a); 

这将需要O(lg(n))时间在最坏的情况下。

但是,如果你想要一个高性能包含操作考虑使用HashSet而不是ArrayList。这需要几乎不变的时间。

0

如果Collections.sort(l)没有得到期望的结果,尝试Collections.sort(l, comparator)其中“比较”是这样的:

class MyComparator implements Comparator<Integer> 
{ 
    public int compare(Integer lhs, Integer rhs) 
    { 
    // perform the desired comparison. 
    } 
} 

编辑:我会离开这件事,但“Mairbek Khadikov”答案似乎是最好的答案。

相关问题