查找数组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

以上是 查找数组JavaScript的多数元素 的全部内容, 来源链接: utcz.com/z/326463.html

回到顶部