算法复习_线性时间求解Majority Vote Algorithm问题

题目来源于Leecode上的Majority Element问题

Majority Element:在一个序列中出现了至少n/2的下界次

使用排序算法取中位数则需要Nlogn

http://www.cs.utexas.edu/~moore/best-ideas/mjrty/

介绍了一种线性时间内的算法:

代码:

public class Solution {
    public int majorityElement(int[] num) {

        int major=num[0], count = 1;
        for(int i=1; i<num.length;i++){
            if(count==0){
                count++;
                major=num[i];
            }else if(major==num[i]){
                count++;
            }else count--;
            
        }
        return major;
    }
}

 

posted on 2017-11-12 20:41  mdumpling  阅读(212)  评论(0编辑  收藏  举报

导航