美文网首页
2020年 Moore majority vote algori

2020年 Moore majority vote algori

作者: Lrc123 | 来源:发表于2020-03-13 18:41 被阅读0次
    image.png
    第一眼看到这个题目,想到的是使用Map来统计出现频次,然后遍历找出频次大于n/2的元素。
    class Solution {
        public int majorityElement(int[] nums) {
            Map<Integer, Integer> map = new HashMap<>();
            for(Integer item: nums){
                if(null != map.get(item)){
                    map.put(item, map.get(item) + 1);
                }else
                    map.put(item,1);
            }
            for(Integer freq: map.keySet()){
                if(map.get(freq) > (nums.length / 2))
                    return freq;
            }
            return -1;
        }
    }
    

    但是显而易见的是:没有用上n/2这个设定。
    其实这个看似简单的问题有一个特殊的解法,就是我们要说的Boyer–Moore majority vote algorithm :摩尔投票法
    知乎上有老哥给出了非常形象的解释:

    核心是对拼消耗:类似我们玩的即时战略游戏:魔兽争霸,三国群英传等。假设地图上有一家(称作红色军)拥有所有军队中一半以上的小兵,在直接对拼下不虚任何对手(不同队伍小兵1v1地同归于尽),其他队伍像蓝色、绿色、紫色等,有可能会互相消耗,但是最后留在地图上的一定是同一队人数最多的红色。

    如何理解摩尔投票算法? - 知乎用户的回答 - 知乎
    https://www.zhihu.com/question/49973163/answer/617122734
    具体实现:

    class Solution{
        public int majorityElement(int[] nums){
        int res = 0;
            int count = 0;
    
            for (int num : nums) {
                if (count == 0) {
                    res = num;
                }
                count += (num == res) ? 1 : -1;
            }
    
            return res;
        }
    

    有兴趣的话还可以再看一下下面这个
    wiki上的伪代码:

    The algorithm maintains in its local variables a sequence element and a counter, with the counter initially zero. 
    It then processes the elements of the sequence, one at a time. When processing an element x, if the counter is zero, the algorithm stores x as its remembered sequence element and sets the counter to one. 
    Otherwise, it compares x to the stored element and either increments the counter (if they are equal) or decrements the counter (otherwise). 
    At the end of this process, if the sequence has a majority, it will be the element stored by the algorithm. This can be expressed in pseudocode as the following steps:
    
    Initialize an element m and a counter i with i = 0
    For each element x of the input sequence:
    If i = 0, then assign m = x and i = 1
    else if m = x, then assign i = i + 1
    else assign i = i − 1
    Return m
    Even when the input sequence has no majority, the algorithm will report one of the sequence elements as its result. 
    However, it is possible to perform a second pass over the same input sequence in order to count the number of times the reported element occurs and determine whether it is actually a majority. This second pass is needed, as it is not possible for a sublinear-space algorithm to determine whether there exists a majority element in a single pass through the input.
                
    

    --- 引用自wikipedia

    相关文章

      网友评论

          本文标题:2020年 Moore majority vote algori

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