हमें आकार n का एक ऐरे दिया गया है, और हमें मेजोरिटी एलिमेंट ढूंढना है। मेजोरिटी एलिमेंट वह एलिमेंट है जो [ n/2 ] से अधिक बार आता है।
उदाहरण
const arr = [2, 4, 2, 2, 2, 4, 6, 2, 5, 2]; const majorityElement = (arr = []) => { const threshold = Math.floor(arr.length / 2); const map = {}; for (let i = 0; i < arr.length; i++) { const value = arr[i]; map[value] = map[value] + 1 || 1; if (map[value] > threshold) return value }; return false; }; console.log(majorityElement(arr));आउटपुट
कंसोल में आउटपुट होगा -
2