本文介绍了如何在Java中查找数组中的第二大数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在练习一些MIT Java作业.但是,我不确定如何找到第二大数字. http://ocw.csail.mit.edu/f/13

I'm just practicing some MIT java assignments. But, I'm not sure how to find the second largest number. http://ocw.csail.mit.edu/f/13

  public class Marathon {
    public static void main(String[] arguments) {
        String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil",
                "Matt", "Alex", "Emma", "John", "James", "Jane", "Emily",
                "Daniel", "Neda", "Aaron", "Kate" };

        int[] times = { 341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412,
                393, 299, 343, 317, 265 };

        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i] + ": " + times[i]);
        }

        System.out.println();
        System.out.println("Largest Timing " + Largest(times));
        System.out.println();

    }

    public static int Largest(int[] times) {
        int maxValue = times[0];

        for (int i = 1; i < times.length; i++) {
            if (times[i] > maxValue) {
                maxValue = times[i];
            }
        }
        return maxValue;
    }

}

推荐答案

仅对数组进行排序即可找到顺序统计信息太浪费了.您可以通过遵循与现有算法相似的算法来查找第二大元素,并使用一个代表第二大数字的附加变量.

Sorting the array simply to find an order statistics is too wasteful. You can find the second largest element by following an algorithm that resembles the one that you already have, with an additional variable representing the second largest number.

当前,下一个元素可以大于最大值或等于/小于最大值,因此单个if就足够了:

Currently, the next element could be larger than the max or equal to/smaller than the max, hence a single if is sufficient:

if (times[i] > maxValue) {
    maxValue = times[i];
}

要考虑两个变量,下一个元素可能是

With two variables to consider, the next element could be

  • 大于最大值-最大值变为第二大,而下一个元素变为最大值
  • 比最大值小,但大于第二大元素-下一个元素变为第二大元素.
  • Greater than the max - the max becomes second largest, and the next element becomes the max
  • Smaller than the max but greater than the second largest - the next element becomes second largest.

必须特别注意初始状态.查看前两个项目,然后将较大的项分配给max,将较小的项分配给第二个最大项.如果有一个元素,则从第三个元素开始循环.

A special care must be taken about the initial state. Look at the first two items, and assign the larger one to the max and the smaller to the second largest; start looping at the element number three, if there is one.

您可以在此处进行编码:

Here is how you can code it:

if (times[i] > maxValue) {
    secondLargest = maxValue;
    maxValue = times[i];
} else if (times[i] > secondLargest) {
    secondLargest = times[i];
}

这篇关于如何在Java中查找数组中的第二大数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 11:15