5

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

我找到的代码:

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

4 回答 4

7

做就是了:

else if (arr[i] > secondLargest && arr[i] != largest) {
    secondLargest = arr[i];
}
于 2013-09-07T13:22:04.357 回答
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);

   }
于 2013-09-07T13:21:30.883 回答
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];
        }
于 2013-09-07T13:23:25.563 回答
0

你需要添加两个:

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

          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];
                 }
          }
    
于 2013-09-07T13:27:04.803 回答