Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
chencl1986 opened this issue Nov 14, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接: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;
    }
  }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant