为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕尼黑8549860 2019-12-02 12:43:24
所以我有一个未排序的数字数组int[] anArray = { 1, 5, 2, 7 };,我需要同时获取值和数组中最大值的索引(即7和3),我该怎么做?
查看完整描述

3 回答

?
森林海

TA贡献2011条经验 获得超2个赞

这不是最迷人的方法,但是有效。


(必须有using System.Linq;)


 int maxValue = anArray.Max();

 int maxIndex = anArray.ToList().IndexOf(maxValue);


查看完整回答
反对 回复 2019-12-02
?
慕村9548890

TA贡献1884条经验 获得超4个赞

int[] anArray = { 1, 5, 2, 7 };

// Finding max

int m = anArray.Max();


// Positioning max

int p = Array.IndexOf(anArray, m);


查看完整回答
反对 回复 2019-12-02
?
慕桂英4014372

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)更快的方法。


查看完整回答
反对 回复 2019-12-02
  • 3 回答
  • 0 关注
  • 1406 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信