码迷,mamicode.com
首页 > 其他好文 > 详细

229. Majority Element II

时间:2016-10-22 14:07:12      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:技术分享   nim   turn   style   ret   代码   大于   images   element   

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]

229. Majority Element II

标签:技术分享   nim   turn   style   ret   代码   大于   images   element   

原文地址:http://www.cnblogs.com/renyualbert/p/5987158.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!