Leetcode #169 Majority Element

7/30/2016 posted in  算法 comments

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.

Build a hash for the result, if a num is not in the hash, then make the hash[num] counts 1, else make the hash[num]+1.

To get the majority element of the array, just get the key with the max value in this hash.

# @param {Integer[]} nums
# @return {Integer}
def majority_element(nums)
  hash = Hash.new
  
  nums.each do |num| 
    if hash.has_key? num
      hash[num] += 1
    else
      hash[num] = 1
    end
  end
  result = hash.key(hash.values.max)
  return result
end