JavaScript 查找数组中的第三大数字
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

