美文网首页
169. Majority Element

169. Majority Element

作者: AlanGuo | 来源:发表于2016-10-04 14:46 被阅读0次

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:
用 HashMap 的 key-value pair 来存取每个元素出现的次数。每当放入一个元素后,检查当前该元素出现次数是否大于等于 n/2 +1,如果是则该元素为 Majority Element。

public class Solution 
{
    public int majorityElement(int[] nums) 
    {
        int m = nums.length / 2 + 1;
        HashMap<Integer, Integer> hm = new HashMap<>();
        for(int i : nums)
        {
            int newCount = hm.getOrDefault(i, 0);
            newCount += 1;
            if(newCount >= m)
                return i;
            hm.put(i, newCount);
        }
        return 0;
    }
}

唯一坑爹的就是“more than ⌊ n/2 ⌋times”……导致提交一次不过。⌊ n/2 ⌋难道不是 n/2 + 1 么?more than 它不就是 **> (n/2 + 1) **的意思么?谁知道这个“向上取整”形同虚设啊。

ps:
HashMap 简直神器。
HashMap 的 getOrDefault(key, defaultValue)方法是神器中的神器。

相关文章

网友评论

      本文标题:169. Majority Element

      本文链接:https://www.haomeiwen.com/subject/xfzjyttx.html