JavaScript 中找出数组中的多数元素


我们获得了一个大小为 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

更新于: 21-Nov-2020

740 次浏览

开启您的 职业

完成课程获得认证

开始学习
广告
© . All rights reserved.