21xrx.com
2025-03-26 09:26:29 Wednesday
文章检索 我的文章 写文章
Java实现数组最大值与次大值的差
2023-06-15 20:17:43 深夜i     --     --
Java 数组 最大值 次大值

在Java中,想要求一个数组中的最大值和次大值的差,可以使用以下方法实现:

1. 定义一个长度为2的数组max,用来存储最大值和次大值的值;

2. 遍历整个数组,每次比较当前元素和max中的元素,更新max数组;

3. 返回max[0]-max[1]即为最大值和次大值的差。

代码实现如下:

public static int maxMinusSecondMax(int[] arr) {
  int[] max = new int[2];
  max[0] = Integer.MIN_VALUE;
  max[1] = Integer.MIN_VALUE;
  for(int i=0; i
    if(arr[i] > max[0]) {
      max[1] = max[0];
      max[0] = arr[i];
    }
    else if(arr[i] > max[1] && arr[i] != max[0]) {
      max[1] = arr[i];
    }
  }
  return max[0] - max[1];
}

  
  

评论区