zoukankan      html  css  js  c++  java
  • 229. Majority Element II

    Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

    Hint:

    1. How many majority elements could it possibly have?
    2. Do you have a better hint? Suggest it!

    这道题考的是摩尔投票法。具体可以参考GrandYang的解释。代码如下

    public IList<int> MajorityElement(int[] nums) {
            int m = 0;
            int n =0;
            int cm =0;
            int cn =0;
            foreach(var num in nums)
            {
                if(m == num) cm++;
                else if(n == num) cn++;
                else if(cm ==0 )
                {
                    cm=1;
                    m =num;
                }
                else if(cn==0)
                {
                    cn=1;
                    n = num;
                }
                else
                {
                    cm--;
                    cn--;
                }
            }
            cm =0;
            cn=0;
            foreach(var num in nums)
            {
                if(m == num) cm++;
                else if(n == num) cn++;
            }
            var res = new List<int>();
            if(cm > nums.Count()/3) res.Add(m);
            if(cn > nums.Count()/3) res.Add(n);
            return res;
        }

    注意几个corner case

    [0,0,0], 这个要求第二遍循环的时候必须是if else, 如果不是的话会return [0,0].

    [0,1] 还需要注意一点是最后cm cn是要大于而不是大于等于。不然这个输出回事[0,1]

  • 相关阅读:
    实例天天向上的力量
    实例天天向上的力量
    数字类型及操作
    基本数据类型
    函数与模块
    Turtle库(海龟)
    python猛蛇绘制
    输出函数
    循环语句
    集合
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5987158.html
Copyright © 2011-2022 走看看