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.

我自己的思路是很straightforward的用hashmap来做,key是数组元素,value是该元素出现的次数。最后遍历整个hashmap, 找到出现频率最高的那个就是要求的majority element. 因为题目说了这个majority element是肯定存在的,所以直接等价于找频率最高的那个元素是没有问题的。
时间复杂度:O(N)
空间复杂度:O(N)

class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer, Integer> frequency = new HashMap<>();
        for (int i = 0; i < nums.length; i++){
            if (!frequency.containsKey(nums[i])){
                frequency.put(nums[i], 1);
            } else {
                frequency.put(nums[i], frequency.get(nums[i]) + 1);
            }
        }
        int max = 0;
        int maxNum = 0;
        for (Integer integer : frequency.keySet()){
            if (frequency.get(integer) > max){
                max = frequency.get(integer);
                maxNum = integer;
            }
        }
        return maxNum;
    }
}

这道题还有一种解法,可以达到O(N)的Time complexity, 以及O(1)的Auxiliary space, 即Moore’s Voting Algorithm。 先确定Majority element, 再检查该元素是不是真的是Majority element. 第一步确定Majority element的方法是,先设定majIndex = 0, count = 1, 然后依次遍历后面的元素,如果遇到等于nums[majIndex]的元素,count++;如果遇到不是count–.当count == 0的时候,我们更新majIndex为当前index i, 重设count == 1, 继续刚才的遍历。最后结束for循环后,我们便得到了一个majIndex.

第二部我们则检查nums[majIndex]是不是真的是Majority Element, 则只需要验证它出现的次数大于n / 2就可以了

class Solution {
    public int majorityElement(int[] nums) {
        int majIndex = 0;
        int count = 1;
        for (int i = 1; i < nums.length; i++){
            if (nums[i] == nums[majIndex]){
                count++;
            } else {
                count--;
            }
            if (count == 0){
                majIndex = i;
                count = 1;
            }
        }
        if (isMajorityElement(nums, nums[majIndex])){
            return nums[majIndex];
        }
        return -1;
    }
    
    private boolean isMajorityElement(int[] nums, int majorityElement){
        int times = 0;
        for (int i = 0; i < nums.length; i++){
            if (nums[i] == majorityElement){
                times++;
            }
        }
        if (times >= nums.length / 2){
            return true;
        }
        return false;
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/42c134f2d82e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞