Skip to content

LeetCode题解:169. 多数元素,哈希表,JavaScript,详细注释 #222

@chencl1986

Description

@chencl1986

原题链接:https://leetcode-cn.com/problems/majority-element/

解题思路:

  1. 遍历数组,对每个出现的元素用哈希表计数,当数量大于n/2时,返回当前元素即可。
/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function (nums) {
  let map = new Map(); // 使用Map存储每个元素的的数量

  // 遍历数组
  for (const num of nums) {
    // 统计每个元素的数量
    map.get(num) ? map.set(num, map.get(num) + 1) : map.set(num, 1);

    // 判断数量是否大于n/2,若是则直接返回
    if (map.get(num) > nums.length / 2) {
      return num;
    }
  }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions