JavaScript 查找数组中的第三大数
我们需要编写一个 JavaScript 函数,该函数可以接受一个数字数组。此函数应从中拾取并返回数组中的第三大数。
函数的时间复杂度不得超过 O(n),我们必须在一次迭代中找到这个数。
示例
const arr = [1, 5, 23, 3, 676, 4, 35, 4, 2];
const findThirdMax = (arr) => {
let [first, second, third] = [-Infinity, -Infinity, -Infinity];
for (let el of arr) {
if (el === first || el === second || el === third) {
continue; };
if (el > first) {
[first, second, third] = [el, first, second]; continue; };
if (el > second) {
[second, third] = [el, second]; continue;
};
if (el > third) {
third = el; continue;
};
};
return third !== -Infinity ? third : first;
};
console.log(findThirdMax(arr));输出
控制台中的输出为 −
23
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP