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:
- How many majority elements could it possibly have?
- 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]