题目
给你一个数组,如何最快速的找到数组中第二大的元素,用Java和JavaScript代码实现
Java代码实现:
public class SecondLargestElement {
public static int findSecondLargest(int[] arr) {
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int num : arr) {
if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num != largest) {
secondLargest = num;
}
}
return secondLargest;
}
public static void main(String[] args) {
int[] arr = {5, 10, 3, 8, 15};
int secondLargest = findSecondLargest(arr);
System.out.println("Second largest element: " + secondLargest);
}
}
JavaScript代码实现:
function findSecondLargest(arr) {
let largest = Number.MIN_SAFE_INTEGER;
let secondLargest = Number.MIN_SAFE_INTEGER;
for (let num of arr) {
if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num !== largest) {
secondLargest = num;
}
}
return secondLargest;
}
let arr = [5, 10, 3, 8, 15];
let secondLargest = findSecondLargest(arr);
console.log("Second largest element: " + secondLargest);
总结
无论是Java还是JavaScript,算法的核心思想都是通过遍历数组,同时维护两个变量来记录最大值和第二大值。在遍历过程中,如果遇到比当前最大值大的元素,更新最大值和第二大值;如果遇到比第二大值大但不等于最大值的元素,更新第二大值。最后返回第二大值即可。