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

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

    If you want to find both the min and max at the same time, the loop can be modified as follows:

    int min = int.maxValue;
    int max = int.minValue;
    
    foreach num in someArray {
      if(num < min)
        min = num;
      if(num > max)
        max = num;
    }
    

    This should get achieve O(n) timing.

提交回复
热议问题