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

后端 未结 18 1079
日久生厌
日久生厌 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条回答
  •  心在旅途
    2020-11-27 03:37

    If you are building the array once and want to find the maximum just once, iterating is the best you can do.

    When you want to modify the array and occasionally want to know the maximum element, you should use a Priority Queue. One of the best data structures for that is a Fibonacci Heap, if this is too complicated use a Binary Heap which is slower but still good.

    To find minimum and maximum, just build two heaps and change the sign of the numbers in one of them.

提交回复
热议问题