题目来源于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;
    }
}

 

相关文章:

  • 2021-08-15
  • 2022-12-23
  • 2021-06-09
  • 2022-12-23
  • 2022-12-23
  • 2021-06-21
  • 2021-04-19
  • 2021-11-09
猜你喜欢
  • 2022-12-23
  • 2021-09-01
  • 2021-07-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案