用最基础的java循环方法实现设计一个方法, 参数为int数组, 求数组中第二大的数,并返回
时间: 2023-02-12 12:43:36 浏览: 64
```
public int findSecondLargest(int[] arr) {
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second && arr[i] < first) {
second = arr[i];
}
}
return second;
}
```
相关问题
用最基础的java循环方法实现并注释设计一个方法, 参数为int数组, 求数组中第二大的数,并返回,
```java
/**
* 求数组中第二大的数
* @param arr int数组
* @return 第二大的数
*/
public static int getSecondMax(int[] arr) {
int max = Integer.MIN_VALUE;
int secondMax = Integer.MIN_VALUE;
// 遍历数组
for (int i = 0; i < arr.length; i++) {
// 如果当前数比最大值大
if (arr[i] > max) {
// 更新第二大值为最大值
secondMax = max;
// 更新最大值
max = arr[i];
} else if (arr[i] > secondMax) {
// 如果当前数比第二大值大但小于最大值
// 更新第二大值
secondMax = arr[i];
}
}
return secondMax;
}
```
用Java 设计一个方法, 参数为int数组, 求数组中第二大的数,并返回
```java
public static int findSecondLargest(int[] nums) {
int firstLargest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int num : nums) {
if (num > firstLargest) {
secondLargest = firstLargest;
firstLargest = num;
} else if (num > secondLargest && num != firstLargest) {
secondLargest = num;
}
}
return secondLargest;
}
```
这是一个用 Java 实现的方法,参数为 int 数组,可以求出数组中的第二大数,并将其返回。这个方法定义了两个变量 firstLargest 和 secondLargest,分别用来存储数组中的第一大数和第二大数。使用 for 循环遍历数组中的每一个数,对于当前遍历到的数 num,如果它大于 firstLargest,那么将 secondLargest 的值赋给 firstLargest,再将 num 的值赋给 secondLargest;否则如果 num 大于 secondLargest 且不等于 firstLargest,那么将 num 的值赋给 secondLargest。最后,返回 secondLargest。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)