3 回答
TA贡献2011条经验 获得超2个赞
这不是最迷人的方法,但是有效。
(必须有using System.Linq;)
int maxValue = anArray.Max();
int maxIndex = anArray.ToList().IndexOf(maxValue);
TA贡献1884条经验 获得超4个赞
int[] anArray = { 1, 5, 2, 7 };
// Finding max
int m = anArray.Max();
// Positioning max
int p = Array.IndexOf(anArray, m);
TA贡献1871条经验 获得超13个赞
如果索引未排序,则必须至少遍历数组一次以找到最大值。我会使用一个简单的for循环:
int? maxVal = null; //nullable so this works even if you have all super-low negatives
int index = -1;
for (int i = 0; i < anArray.Length; i++)
{
int thisNum = anArray[i];
if (!maxVal.HasValue || thisNum > maxVal.Value)
{
maxVal = thisNum;
index = i;
}
}
这比使用LINQ或其他单线解决方案的方法更为冗长,但可能更快一些。确实没有比O(N)更快的方法。
- 3 回答
- 0 关注
- 1615 浏览
添加回答
举报
