Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

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