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

后端 未结 18 1039
日久生厌
日久生厌 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:45

    You have to loop through the array, no other way to check all elements. Just one correction for the code - if all elements are negative, maxValue will be 0 at the end. You should initialize it with the minimum possible value for integer.
    And if you are going to search the array many times it's a good idea to sort it first, than searching is faster (binary search) and minimum and maximum elements are just the first and the last.

提交回复
热议问题