Sunday, January 11, 2015

LeetCode 169: Majority Element

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.
public class Solution {
    public int majorityElement(int[] num) {
        // Adopt HashMap to save the number and corresponding apear times
        int n = num.length;
        Map<Integer, Integer> map = new HashMap<>();
        
        for (int i = 0; i < n; i++)
        {
            if (!map.containsKey(num[i]))
                map.put(num[i], 1);
            else
                map.put(num[i], map.get(num[i])+1);
        }
        
        int maxNum = 0;
        int maxTimes = 0;
        
        for (int number : map.keySet())
        {
            if (map.get(number) > maxTimes)
            {
                maxNum = number;
                maxTimes = map.get(number);
            }
        }
        
        return maxNum;
    }
}

No comments:

Post a Comment