เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้อาร์เรย์ของ Numbers ฟังก์ชันควรเลือกและส่งคืนตัวเลขสูงสุดอันดับสามจากอาร์เรย์
ความซับซ้อนของเวลาของฟังก์ชันของเราจะต้องไม่เกิน 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