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

时间:2012-11-13 01:17:00

标签: java arrays

我正在练习一些麻省理工学院的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;
    }

}

10 个答案:

答案 0 :(得分:7)

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

  • 保持largestValuesecondLargestValue
  • 为每个元素循环遍历整个数组:
    • 检查当前元素是否大于largestValue
      • 如果是,请将largestValue分配给secondLargestValue,然后将当前元素分配给largestValue(将其视为将所有内容向下移动1)
      • 如果没有,请检查当前元素是否大于secondLargestValue
        • 如果是,请将当前元素分配给secondLargestValue
        • 如果没有,请不要做任何事。

O(n)运行时间

O(1)空间要求

答案 1 :(得分:3)

对数组进行排序只是为了找到order statistics太浪费了。您可以通过遵循类似于您已有的算法的算法找到第二大元素,其他变量代表第二大数字。

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

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

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

  • 大于最大值 - 最大值变为第二大,下一个元素变为最大值
  • 小于最大值但大于第二大 - 下一个元素成为第二大元素。

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

以下是编码方式:

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

答案 2 :(得分:1)

一般来说:

有两个值 - “最大”和“notQuite”。

将两者初始化为-9999或其他任何内容。

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

另一方面,如果数字小于“最大”但 大于“notQuite”,请将“notQuite”设置为该数字。

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

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

答案 3 :(得分:1)

    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);
}

答案 4 :(得分:0)

PHP ALGO

如果给$ 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 

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

答案 5 :(得分:0)

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;

    }

答案 6 :(得分:0)

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;

答案 7 :(得分:0)

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);
}

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

答案 8 :(得分:0)

如果两次出现最大次数并且一次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);
    }
}

答案 9 :(得分:0)

找到给定数组中的第二大元素:

public static void findSecondMax(){
        int[] arr = {3, 2, 20, 4, 1, 9, 6, 3, 8};

        int max = 0;
        int secondMax = 0;

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

            if(max < arr[i]) max = arr[i];

            if((max > arr[i]) && (secondMax < arr[i])) secondMax = arr[i];

        }

        System.out.println(secondMax);
    }