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

[英]I have a list of integers , how to sort it?


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?

我认为调用l.contains很慢,如何对列表进行排序。排序后,l.contains表现得更快吗?

Is there any sortedList I can use directly?

有没有我可以直接使用的sortedList?

7 个解决方案

#1


13  

It can't get simpler than this.

它不能比这更简单。

Collections.sort(l);

#2


7  

Sorting of list would not make contains operation faster. It still be O(n) in worst case.

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

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.

在最坏的情况下,这将花费O(lg(n))时间。

But if you want a high performance contains operation consider using HashSet instead of ArrayList. It takes nearly constant time.

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

#3


4  

You can use Collections.sort(l);

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

#4


2  

The sort() method from Collections can help you sort your ArrayList.

Collections中的sort()方法可以帮助您对ArrayList进行排序。

#5


1  

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.)

ArrayList上的contains()不假设数组已排序,即使它是。您将需要使用某种类型的集合(HashSet将为您提供最佳的查找性能,并且LinkedHashSet将保留订单。即使TreeList也会为您提供更好的性能。)

#6


0  

TreeSet may be useful for you.

TreeSet可能对您有用。

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

#7


0  

If Collections.sort(l) does not give the desired result, try Collections.sort(l, comparator) where "comparator" is something like this:

如果Collections.sort(l)没有给出所需的结果,请尝试Collections.sort(l,comparator),其中“comparator”是这样的:

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.

编辑:我会留下这个,但“Mairbek Khadikov”的答案似乎是最好的答案。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2012/01/16/87a0e247703d4b93d0179166a00490b.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告