हमें एक 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