C#查找最高的数组值和索引

所以我有一个未排序的数字数组int[] anArray = { 1, 5, 2, 7 };,我需要同时获取值和数组中最大值的索引(即7和3),我该怎么做?



慕尼黑8549860
浏览 1425回答 3
3回答

森林海

这不是最迷人的方法,但是有效。(必须有using System.Linq;) int maxValue = anArray.Max(); int maxIndex = anArray.ToList().IndexOf(maxValue);

慕村9548890

int[] anArray = { 1, 5, 2, 7 };// Finding maxint m = anArray.Max();// Positioning maxint p = Array.IndexOf(anArray, m);

慕桂英4014372

如果索引未排序,则必须至少遍历数组一次以找到最大值。我会使用一个简单的for循环:int? maxVal = null; //nullable so this works even if you have all super-low negativesint index = -1;for (int i = 0; i < anArray.Length; i++){&nbsp; int thisNum = anArray[i];&nbsp; if (!maxVal.HasValue || thisNum > maxVal.Value)&nbsp; {&nbsp; &nbsp; maxVal = thisNum;&nbsp; &nbsp; index = i;&nbsp; }}这比使用LINQ或其他单线解决方案的方法更为冗长,但可能更快一些。确实没有比O(N)更快的方法。
打开App,查看更多内容
随时随地看视频慕课网APP