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
廣告