我需要一种简单,轻量级的方法来获取双精度数组的最大值和最小值.诀窍是我只需要数组中两个索引之间的最大值和最小值.
内置的arrayOfDoubles.Max()和arrayOfDoubles.Min()将无法工作,因为它们会检查整个数组.
此代码将不断运行,并且需要有点高效.也就是说,简单性和可读性比速度更重要.
这是获得两个索引之间的最大值和最小值的一种方法:
double[] array = new double[8] { 3, 1, 15, 5, 11, 9, 13, 7 };
int startIndex = 3;
int endIndex = 6;
// Get max and min between these two indexes in the array
double max = GetMax(array, startIndex, endIndex);
double min = GetMin(array, startIndex, endIndex);
Console.WriteLine("Max = " + max + ", Min = " + min);
Run Code Online (Sandbox Code Playgroud)
以下是GetMax的代码,GetMin非常相似:
private static double GetMax(double[] array, int startIndex, int endIndex)
{
double max = double.MinValue;
for (int i = startIndex; i <= endIndex; i++)
{
// Increase max with each bigger value
max = Math.Max(max, array[i]);
}
return max;
}
Run Code Online (Sandbox Code Playgroud)
并输出: Max = 13, Min = 5
问题:我可以通过哪些其他方式获得可能更简单且不需要太多开销的相同结果?
var list = array.Skip(startIndex).Take(endIndex - startIndex + 1).ToList();
var min = list.Min();
var max = list.Max();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2156 次 |
| 最近记录: |