Wednesday, May 3, 2017

Majority Element -LeetCode

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.
Thoughts:


Runtime: O(n), Space: O(n) — Hash table: Maintain a hash table of the counts of each element, then find the most common one.

Java Solution:

public class Solution {
    public int majorityElement(int[] nums) {
        int n = nums.length;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int elem : nums){
            if(map.containsKey(elem)){
                map.put(elem, map.get(elem) + 1);
            }else{
                map.put(elem, 1);
            }
        }
        for(int item : map.keySet()){
            if(map.get(item) > n / 2){
                return item;
            }
        }
        return -1;
    }
}

No comments:

Post a Comment