java 如何最有效地在 LinkedList 中查找最大和最小元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12053500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:25:34  来源:igfitidea点击:

How to find max and min element in a LinkedList most efficiently?

javadata-structures

提问by h4ck3d

I have a linked list in Java ,say , LinkedList<T> list = new LinkedList<T>();and I need to find the max / min element in it most efficiently , how can I do it?

比如说,我有一个 Java 链表,LinkedList<T> list = new LinkedList<T>();我需要最有效地在其中找到最大/最小元素,我该怎么做?

How can I use Collections.max()function to find the max element from my linked list? What is the time complexity of this function ?

如何使用Collections.max()函数从链表中查找最大元素?这个函数的时间复杂度是多少?

回答by Peter Lawrey

The time complexity is O(n)if you want it to be lower e.g. O(1)you need to use a different data structure such as a TreeSet.

时间复杂度是O(n)如果您希望它更低,例如O(1)您需要使用不同的数据结构,例如 TreeSet。

how can i use Collections.max() for LinkedList

我如何将 Collections.max() 用于 LinkedList

List<Integer> list = ...
Integer max = Collections.max(list);

回答by Adam Sznajder

ArrayList<Integer> numbers = new ArrayList<Integer>();
/* fill with values */
Integer max = Collections.max(numbers);

回答by Amit Deshpande

Java Doc

Java文档

This method iterates over the entire collection, hence it requires time proportional to the size of the collection. (O(n))

此方法迭代整个集合,因此它需要与集合大小成正比的时间。(在))

Usage

用法

public class Test
{
  public static void main(String args[])
  {
    // create an LinkedList object
    LinkedList<Integer> list = new LinkedList<Integer>();

    // Add elements to LinkedList
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(4);
    list.add(5);

    //Use Max Method
    System.out.println(Collections.max(list));
}
}


回答by Ritam Chakraborty

You can also use stream.max()to get the max value of a LinkedList

您还可以使用stream.max()获取 LinkedList 的最大值

LinkedList<Integer> linkedList = new LinkedList<>();

linkedList.add(1); linkedList.add(2);
linkedList.add(3); linkedList.add(4);

linkedList.stream().max(Integer::compareTo).ifPresent(System.out::println);

Output: 4