首页 > 代码库 > [LeetCode]169 Majority Element

[LeetCode]169 Majority Element

https://oj.leetcode.com/problems/majority-element/

public class Solution {
    public int majorityElement(int[] num) {
        
        int len = num.length;
        int minhit = (len / 2) + 1;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i : num)
        {
            Integer occur = map.get(i);
            if (occur == null)
                occur = 0;
            occur ++;
            
            if (occur >= minhit)
                return i;
            else
                map.put(i, occur);
        }
        // throw exception
        throw new IllegalStateException("input is wrong");
    }
}


[LeetCode]169 Majority Element