mengjian-github / leetcode

leetcode前端题目笔记

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

169. 多数元素

mengjian-github opened this issue · comments

给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

 

示例 1:

输入:nums = [3,2,3]
输出:3
示例 2:

输入:nums = [2,2,1,1,1,2,2]
输出:2
 

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/majority-element
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

利用map的方案:

/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function(nums) {
    const map = new Map();
    const n = Math.floor(nums.length / 2);

    for (const num of nums) {
        if (!map.has(num)) {
            map.set(num, 0);
        }
        const count = map.get(num) + 1;
        if (count > n) {
            return num;
        }
        map.set(num, count);
    }

    return -1;
};

其他解法有待进一步探究