编写程序以查找数组中Max项的索引

She*_*riy 3 c# arrays console-application

在C#中编写一个控制台应用程序,以在数组中查找索引i,该索引是数组中的最大数字.

如果数组中的最大元素出现多次,则需要显示最小索引.

如果数组为空,则输出-1.

请告诉我我的代码有什么问题?

a = { 1, 2, 46, 14, 64, 64 };例如,如果我输入数组,它将返回0,而它应该返回 4.

  public static void Main()
  {
     double[] a = { 1, 9, 9, 8, 9, 2, 2 };
     Console.WriteLine(MaxIndex(a));
  }

  public static double MaxIndex(double[] array)
  {
     var max = double.MinValue;
     int maxInd = 0, maxCount = 0;
     int minIndex = 0;
     var min = double.MaxValue;
     for (var i = 0; i < array.Length; i++)
     {
        if (min > array[i])
        {
           min = array[i];
           minIndex = i;

        }
        if (max == array[i])
           maxCount++;
        if (max < array[i])
        {
           maxCount = 1;
           max = array[i];
           maxInd = i;
        }
     }

     if (array.Length == 0)
        return -1;
     if (maxCount > 1)
        return minIndex;
     return maxInd;
  }
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 8

您的计算是正确的,但您返回的是错误的变量minIndex而不是maxIndex.不要在方法中做超过必要的事情.这也计算了最小指数和计数出现频率,然后它对结果没有任何作用.这是一个紧凑版本:

public static int MaxIndex(double[] array)
{
    var max = double.MinValue;
    int maxInd = -1;

    for (int i = 0; i < array.Length; i++)
    {
        if (max < array[i])
        {
            max = array[i];
            maxInd = i;
        }
    }

    return maxInd;
}
Run Code Online (Sandbox Code Playgroud)

它还设置了maxInd = -1哪些是您的要求的一部分.由于MatthewWatsondouble.MinValue对阵列中的重复有异议,因此这是一个优化版本:

public static int MaxIndex(double[] array)
{
    if(array.Length == 0)
        return -1;
    else if (array.Length == 1)
        return 0;

    double max = array[0];
    int maxInd = 0;

    for (int i = 1; i < array.Length; i++)
    {
        if (max < array[i])
        {
            max = array[i];
            maxInd = i;
        }
    }

    return maxInd;
}
Run Code Online (Sandbox Code Playgroud)

如果代码可读性/可维护性更重要并且您不需要花费几毫秒或更少,您可以使用LINQ(仅枚举一次的版本):

int minIndexOfMaxVal = a.Select((num, index) => new {num, index})
    .OrderByDescending(x => x.num)
    .Select(x => x.index)
    .DefaultIfEmpty(-1)
    .First();
Run Code Online (Sandbox Code Playgroud)

这适用于各种序列和类型,不仅适用于数组和双精度数.

  • @MatthewWatson:我添加了一个优化版本 (3认同)