标签:
题目链接https://leetcode.com/problems/majority-element/
这道题最一开始的思路是建立一个hashmap,这样就是 O(n) time和 O(n) space。
但是后来看了一下leetcode给出的官方解答,发现moore voting algorithm很有意思,就记了下来,以后遇到这个问题就用他这个方法了。
以下摘自leetcode
“
Runtime: O(n) — Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
2. If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.
After one pass, the current candidate is the majority element. Runtime complexity = O(n).
”
博主的code
class Solution { public: int majorityElement(vector<int> &num) { int candidate = num[0]; int counter = 0; for(int i = 0; i < num.size(); i++) { if(counter == 0) { candidate = num[i]; counter = 1; } if(candidate == num[i]) counter++; else counter--; } return candidate; } };
至于这个算法为什么是正确的,证明在发明者的这篇paper中 http://www.cs.rug.nl/~wim/pub/whh348.pdf
标签:
原文地址:http://www.cnblogs.com/walcottking/p/4430863.html