最大的第二个数字

时间:2013-09-07 13:15:18

标签: java

我到处搜索找到第二大数字的解决方案,但我在所有网站都有一个解决方案,这是错误的。

我找到的代码:

public static void main(String[] args) {
    int arr[] = { 1, 23, 47, 81, 92, 88, 52, 48, 56, 66, 65, 76, 71, 85,
                   49, 53, 56, 61, 65, 84 };
    secondLargeNumber(arr);
}

public static void secondLargeNumber(int[] arr) {
    int largest = arr[0];
    int secondLargest = arr[0];
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] > largest) {
            secondLargest = largest;
            largest = arr[i];
        } else if (arr[i] > secondLargest) {
            secondLargest = arr[i];
        }
    }
    System.out.println("second largest in array is:" + secondLargest);

}

代码工作正常,但如果我将输入序列更改为:

 int arr[] = { 11, 10, 11, 2, 3, 4, 5, 6, 7, 8};

输出将是:

second largest in array is:11

我真的不知道该怎么做!

4 个答案:

答案 0 :(得分:7)

只是做:

else if (arr[i] > secondLargest && arr[i] != largest) {
    secondLargest = arr[i];
}

答案 1 :(得分:0)

 public static void secondLargeNumber(int[] arr) {
          int largest = Integer.MIN_VALUE;
          int secondLargest = Integer.MIN_VALUE;
          for (int i = 0; i < arr.length; i++) {
                 if (arr[i] > largest) {
                       secondLargest = largest;
                       largest = arr[i];

                 } else if (arr[i] > secondLargest && arr[i] != largest) {
                       secondLargest = arr[i];

                 }
          }
          System.out.println("second largest in array is:" + secondLargest);

   }

答案 2 :(得分:0)

问题来自: -

int largest = arr[0];
int secondLargest = arr[0];

尝试用最少的数字初始化变量:

 int secondlargest = Integer.MIN_VALUE;
 int largest = Integer.MIN_VALUE;

这个怎么样: -

   int secondlargest = Integer.MIN_VALUE;
        int largest = Integer.MIN_VALUE;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter array values: ");
        int arr[] = new int[5];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = input.nextInt();
            if (largest < arr[i]) {
                secondlargest = largest;
                largest = arr[i];
            }
            if (secondlargest < arr[i] && largest != arr[i])
                secondlargest = arr[i];
        }

答案 3 :(得分:0)

你需要两个补充:

  1. 正如其他帖子所建议的那样!=最大的支票
  2. 如果最大值和次最大值都以相同的值开始,请尽快将secondlargest切换为较小的值。

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