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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP