【问题标题】:finding second max value in array [duplicate]在数组中找到第二个最大值[重复]
【发布时间】:2016-11-30 02:47:52
【问题描述】:

在我的数组中查找第二大数字时遇到问题。问题是,它不适用于我的所有示例。 从键盘读取数字后,我将它们放入方法 test 中,然后对它们进行排序.. 示例:(用户输入)1、2、3、4、5、6、7、8、9, 10 退出:10,9,..3,2,1 现在我想用 for 循环显示第二大数字.. **任务是:如果可能的话,找到第二大的数字,如果不是CW("error") **

在代码中注释 //这里我不知道如何正确地写这部分代码。

我希望我的问题有意义...

    public static int test(int[] polje)
    {

        int temp = 0;
        Console.WriteLine();
        for (int c = 0; c < polje.Length; c++)
        {
            for (int b = c + 1; b < polje.Length; b++)
            {
                if (polje[c] > polje[b])
                {
                    temp = polje[c];
                    polje[c] = polje[b];
                    polje[b] = temp;

                }

            }

        }

        int secondlargest = 0;



        //HERE

        for (int i = polje.Length - 1; i >= 0; i--)
        {
            if (polje[polje.Length - 2] == polje[polje.Length - 1] || polje[polje.Length - 2] == 0)
            {
                Console.WriteLine("Wrong!");
                break;
            }
            else
            {
                Console.WriteLine("Second largest number is :{0}", polje[polje.Length - 2]);
                secondlargest = polje[polje.Length - 2];
                break;
            }
        }


        return secondlargest;

    }
    static void Main(string[] args)
    {

        int[] polje = new int[10];
        Console.WriteLine("Enter values");
        for (int i = 0; i < 10; i = i + 1)
        {

            polje[i] = int.Parse(Console.ReadLine());
            if (polje[i] == 0)
            {
                break;
            }
        }
        test(polje);

        Console.ReadLine();
    }
}

}

【问题讨论】:

  • 这是作业吗?因为您使用 List 和 sort,或 LINQ 和 OrderByDescending 和 Take(2) 来获取两个最大值。
  • 如果您已经对它们进行了排序,那么第二个 for 循环的意义何在?根据您是按升序还是降序排序,只要您的数组有两个以上的记录,您就可以选择数组的第二个索引或数组的倒数第二个索引。
  • 这是为了我的家庭作业.. 问题是我必须避免一些输入数字,如果这有意义的话.. 示例:(输入)1、2、2、0 输出:第二大是 1 . (input 2) 2, 1, 1, 0 输出2:第二大是1。
  • 你的意思是你必须避免重复的条目。

标签: c# arrays


【解决方案1】:

很简单:

var secondMaxValue = yourArray.OrderByDescending(x=> x).Skip(1).FirstOrDefault();

【讨论】:

  • 你可能应该提到using System.Linq;是必需的
  • 如果有两个相同的数字并且你不希望你可以使用 Distinct()。但是,问题中没有解释在这种情况下究竟需要什么。
  • 我们不能使用 .net 中的任何内容或其他高级功能。
  • @MarkoŠkrilec 如果你不能使用 .net 中的任何东西,那么你就不能使用 C#。
  • @juharr 它用于我的家庭作业.. 我们不能使用所有功能,我真的很生气,因为这样。老师告诉我,我可以通过正常的数组排序和一个遍历数组 [] 的 for 循环向后添加 if 条件来做到这一点。
【解决方案2】:
int GetSecondLargest(int[] a){
    int a0,b0;
    for(int i = 0; i <a.Length;i++){
            if(a[i] > a0){ 
                  b0 = a0;
                  a0 = a[i];
            }else if(a[i] > b0) b0 = a[i];
   }
   return b0;

编辑:格式化很糟糕,但我们的想法是您保留最大值并使用基本条件获取其正下方的值。不需要 Linq。

【讨论】:

  • 您缺少else if(a[i] &gt; b0) b0 = a[i];
  • 谢谢,格式有点搞砸了
猜你喜欢
  • 1970-01-01
  • 2015-11-26
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
  • 2021-02-08
相关资源
最近更新 更多