算法:找出一个数组中出现次数最多的元素

找出一个数组中出现次数最多的元素

  1. 使用对象记录元素出现次数:
function findMostFrequentElement(arr) {
    let count = {};
    let maxCount = 0;
    let mostFrequentElement = null;

    arr.forEach(element => {
        count[element] = (count[element] || 0) + 1;
        if (count[element] > maxCount) {
            maxCount = count[element];
            mostFrequentElement = element;
        }
    });

    return mostFrequentElement;
}

const arr = [1, 5, 3, 5, 5, 3, 4, 5, 2];
console.log(findMostFrequentElement(arr)); // 输出: 5
  1. 使用Map记录元素出现次数:
function findMostFrequentElement(arr) {
    let count = new Map();
    let maxCount = 0;
    let mostFrequentElement = null;

    arr.forEach(element => {
        count.set(element, (count.get(element) || 0) + 1);
        if (count.get(element) > maxCount) {
            maxCount = count.get(element);
            mostFrequentElement = element;
        }
    });

    return mostFrequentElement;
}

const arr = [1, 2, 3, 2, 2, 3, 4, 5, 2];
console.log(findMostFrequentElement(arr)); // 输出: 2
  1. 使用reduce函数结合对象记录元素出现次数:
function findMostFrequentElement(arr) {
    const count = arr.reduce((acc, element) => {
        acc[element] = (acc[element] || 0) + 1;
        return acc;
    }, {});

    let maxCount = 0;
    let mostFrequentElement = null;

    for (const element in count) {
        if (count[element] > maxCount) {
            maxCount = count[element];
            mostFrequentElement = element;
        }
    }

    return mostFrequentElement;
}

const arr = [1, 1, 3, 1, 1, 3, 4, 5, 2];
console.log(findMostFrequentElement(arr)); // 输出: 1

你可能感兴趣的:(前端算法,算法,javascript,前端)