What is the best way to get the minimum or maximum value from an Array of numbers?

后端 未结 18 999
日久生厌
日久生厌 2020-11-27 03:00

Let\'s say I have an Array of numbers: [2,3,3,4,2,2,5,6,7,2]

What is the best way to find the minimum or maximum value in that Array?

Right now,

18条回答
  •  -上瘾入骨i
    2020-11-27 04:02

    Unless the array is sorted, that's the best you're going to get. If it is sorted, just take the first and last elements.

    Of course, if it's not sorted, then sorting first and grabbing the first and last is guaranteed to be less efficient than just looping through once. Even the best sorting algorithms have to look at each element more than once (an average of O(log N) times for each element. That's O(N*Log N) total. A simple scan once through is only O(N).

    If you are wanting quick access to the largest element in a data structure, take a look at heaps for an efficient way to keep objects in some sort of order.

提交回复
热议问题