169. Majority Element

Description

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Solution

/**
 * Solved with hash table
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function(nums) {
    "use strict";
    let majority = Math.floor(nums.length/2);
    let table = {};
    for (let i = 0; i < nums.length; i++) {
        if (table[nums[i]] === undefined) {
            table[nums[i]] = 0;
        }
        table[nums[i]]++;
        if (table[nums[i]] > majority) {
            return nums[i];
        }
    }
};

results matching ""

    No results matching ""