java 如何在Java中找到数组中的第二大数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13354278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:23:21  来源:igfitidea点击:

How to find second largest number in an array in Java?

javaarrays

提问by AppSensei

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

我只是在练习一些 MIT java 作业。但是,我不确定如何找到第二大数字。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;
    }

}

回答by sampson-chen

Instead of resorting to sorting the array, you can simply do the following:

您可以简单地执行以下操作,而不是对数组进行排序:

  • Keep a largestValueand a secondLargestValue
  • Loop through the entire array once, for each element:
    • Check to see if the current element is greater than largestValue:
      • If so, assign largestValueto secondLargestValue, then assign the current element to largestValue(think of it as shifting everything down by 1)
      • If not, check to see if the current element is greater than secondLargestValue
        • If so, assign the current element to secondLargestValue
        • If not, do nothing.
  • 保持一个largestValue和一个secondLargestValue
  • 对于每个元素,遍历整个数组一次:
    • 检查当前元素是否大于largestValue
      • 如果是,则分配largestValuesecondLargestValue,然后将当前元素分配给largestValue(将其视为将所有内容向下移动 1)
      • 如果不是,则检查当前元素是否大于 secondLargestValue
        • 如果是,则将当前元素分配给 secondLargestValue
        • 如果没有,什么都不做。

O(n)run time

O(n)运行时间

O(1)space requirement

O(1)空间要求

回答by dasblinkenlight

Sorting the array simply to find an order statisticsis 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.

仅仅为了查找订单统计信息而对数组进行排序太浪费了。您可以通过遵循类似于您已有的算法的算法来找到第二大元素,并使用一个附加变量表示第二大数字。

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

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

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.
  • 大于最大值- 最大值变为第二大,下一个元素变为最大值
  • 小于最大值但大于第二大- 下一个元素变为第二大。

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

必须特别注意初始状态。查看前两项,将较大的分配给max第二大的,将较小的分配给第二大的;如果存在,则从第三个元素开始循环。

Here is how you can code it:

您可以通过以下方式对其进行编码:

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

回答by Hot Licks

Generally speaking:

通常来说,一般来说:

Have two values -- "largest" and "notQuite".

有两个值——“largest”和“notQuite”。

Initialize both to -9999 or whatever.

将两者都初始化为 -9999 或其他任何值。

Scan through your list. If the number is larger than "largest", set "largest" to that number. But before you do that, copy the old "largest" value to "notQuite".

浏览您的清单。如果数字大于“最大”,则将“最大”设置为该数字。但在此之前,请将旧的“最大”值复制到“notQuite”。

If, on the other hand, the number is smaller than "largest" but islarger than "notQuite", set "notQuite" to that number.

如果,另一方面,数量比“最大的”小,但就是不是“notQuite”,集“notQuite”到这个数字更大。

When you're done examining all the numbers, "notQuite" contains the second-largest.

当您检查完所有数字后,“notQuite”包含第二大数字。

And note that, as you fill in the above numbers, you can also keep a "largestIndex" and "notQuiteIndex" and fill those in with the corresponding array index values, so you can identify the "winning" value. Unfortunately, though, if there are multiple identical "largest" or "secondLargest" values the simple index scheme doesn't work and you need to keep a list of some sort.

并注意,在填写上述数字时,您还可以保留“largestIndex”和“notQuiteIndex”,并用相应的数组索引值填充它们,以便识别“获胜”值。不幸的是,如果有多个相同的“最大”或“第二大”值,那么简单的索引方案不起作用,您需要保留某种列表。

回答by Deepak Sharma

    private void secondLargest(int arr[]){

    int maxOne=arr[0];
    int maxTwo=arr[1];

    for(int i=0;i<arr.length;i++){

        if(arr[i]>maxOne){

            maxTwo=maxOne;
            maxOne=arr[i];
        }else if (arr[i]>maxTwo) {

            maxTwo=arr[i];
        }

    }

    System.out.println(maxOne);
    System.out.println(maxTwo);
}

回答by Mr AJ

PHP ALGO

PHP算法

if $arr is given array

如果给定 $arr 数组

$a = 0; $b = 0; // These are two variables and set their value to minimum
 $i = 0 ; // this is incremental variable
 loop $i till count($arr)   // loop the array using foreach or for-loop till length of array
    if( $arr[i] > $a || $arr[i] > $b) 
       ($a < $b) ? $a = $arr[i]: $b = $arr[i] ; // this is conditional operator 
    loop ends

    echo 'Second largest number is : '. ($a < $b)? $a : $b;  // this is conditional operator and you can output the smallest of final two number 

*The variable declaration and output is different but you can take the logic from it.

*变量声明和输出不同,但您可以从中获取逻辑。

回答by Saurabh

private static int secLargest(int[] numbers) {
        int maxVal = 0;
        int nextMaxVal = 0;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] > maxVal) {
                nextMaxVal = maxVal;
                maxVal = numbers[i];

            }
            if (numbers[i] < maxVal) {
                nextMaxVal = maxVal;
                maxVal = numbers[i];

            }
        }
        return nextMaxVal;

    }

回答by Mircea Stefan

int largest=time[0];
int secondLargest=largest;
for(int i=0;i<time.length;i++){
    if(time[i]>largest){
        secondLargest=largest;
        largest=time[i];
    }
    else if(secondLargest<time[i] && time[i]<largest || secondLargest>=largest)
        secondLargest=time[i];
}
return secondLargest;

回答by Rahul Chauhan

public void findMax(int a[]) {
    int large = Integer.MIN_VALUE;
    int secondLarge = Integer.MIN_VALUE;
    for (int i = 0; i < a.length; i++) {
        if (large < a[i]) {
            secondLarge = large;
            large = a[i];
        } else if (a[i] > secondLarge) {
            if (a[i] != large) {
                secondLarge = a[i];
            }
        }
    }
    System.out.println("Large number " + large + " Second Large  number " + secondLarge);
}

The above code has been tested with integer arrays having duplicate entries, negative values. Largest number and second largest number are retrieved in one pass. This code only fails if array only contains multiple copy of same number like {8,8,8,8} or having only one number.

上面的代码已经用具有重复条目和负值的整数数组进行了测试。一次检索最大数和第二大数。仅当数组仅包含相同数字的多个副本(如 {8,8,8,8} 或只有一个数字)时,此代码才会失败。

回答by Lokesh Verma

It will also extract second largest number if largest number occours two times as well as in a single for loop.

如果最大数出现两次以及在单个 for 循环中,它还将提取第二大数。

import java.util.*;
public class SecondLargestInArray
{
    public static void main(String[] args)
    {
        int arr[] = {99,14,46,47,86,92,52,48,36,66,85,92};
        int largest = arr[0];
        int secondLargest = arr[0];
        System.out.println("The given array is:" );
        for (int i = 0; i < arr.length; i++)
        {
            System.out.print(arr[i]+"\t");
        }

        for (int i = 0; i < arr.length; i++)
        {
            if (arr[i] > largest)
            {
                secondLargest = largest;
                largest = arr[i];
            }
            else if((arr[i]<largest && arr[i]>secondLargest) || largest==secondLargest)
            {
                secondLargest=arr[i];
            }
        }
        System.out.println("\nLargest number is:" + largest);
        System.out.println("\nSecond largest number is:" + secondLargest);
    }
}