Original link: leetcode-cn.com/problems/ma…

Answer:

  1. Iterate over the array, hash each occurrence of the element count, when the number is greater than n/2, return the current element.
/ * * *@param {number[]} nums
 * @return {number}* /
var majorityElement = function (nums) {
  let map = new Map(a);// Use Map to store the number of each element

  // go through the number group
  for (const num of nums) {
    // Count the number of each element
    map.get(num) ? map.set(num, map.get(num) + 1) : map.set(num, 1);

    // Check whether the number is greater than n/2, if so, return directly
    if (map.get(num) > nums.length / 2) {
      returnnum; }}};Copy the code