查找数组的多数元素 JavaScript
javascriptweb developmentfront end technologyobject oriented programming
给定一个大小为 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