Chúng ta cần viết hàm JavaScript nhận vào mảng số. Hàm chọn và trả về số lớn thứ ba từ mảng.
Độ phức tạp thời gian không được vượt quá O(n), phải tìm số trong một lần lặp duy nhất.
Ví dụ
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));Kết quả
Kết quả in ra console:
23