网址:https://leetcode.com/problems/majority-element/
参考:https://blog.csdn.net/u014248127/article/details/79230221
- 可以直接通过map解决
- 利用神奇的 摩尔投票算法( Boyer-Moore Voting Algorithm)
不断的消去两个不同的数,最后剩下的数肯定是所求的众数!
细节:
- 若第一个数的出现次数不止 1,则“消去”意味着次数-1
- 如果两数相同,要将此数的次数累加
class Solution { public: int majorityElement(vector<int>& nums) { int candicate; int count = 0; for(int i : nums) { if(count == 0) candicate = i; if(candicate == i) count++; else count--; } return candicate; } };