Majority Element | LeetCode 169

AFFILIATE LINKS

Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard

Here is the full implementation.

/**
 * @param {number[]} nums
 * @return {number}
 */
let majorityElement = function(nums) {
  if (nums.length === 1) {
    return nums[0];
  }

  let half = nums.length / 2;
  let elementCount = new Map();

  for (let num of nums) {      
    if (!elementCount.has(num)) {
        elementCount.set(num, 1);
    } else {
        elementCount.set(num, elementCount.get(num) + 1);
    }
      
    if (elementCount.get(num) > half) {
      return num;
    }
  }

  return -1;
};