LeetCode169——Majority Element
阿新 • • 發佈:2019-02-15
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
int majorityElement(vector &num) { }
題目大意
給定size 為n的陣列,查找出主元素,就是出現次數大於n/2次的元素。你可以假定陣列非空,而且主元素一定存在。
分析
首先肯定,這樣的主元素只有一個,因為出現次數大於n/2。如何找到它呢?很暴力的做法是,兩輪迴圈,然後把他找出來。時間複雜度是 O(n*n),這顯然不是很好的方法。下面是我的一種解法:
int majorityElement(vector<int> &num) { std::map<int, int> im; for (int i = 0; i < num.size(); ++i){ map<int, int>::iterator it = im.find(num[i]); if (it == im.end()) { im[num[i]] = 1; } else { im[num[i]]++; } if (im[num[i]] > num.size()/2) { return num[i]; } } return 0; }
這種解法還不是最好的,就這問題而已,有一種演算法叫 Moore’s Voting Algorithm,由Robert S.Boyer 和J Strother Moore於1980年發明,是線性時間複雜度。
int majorityElement(vector<int> &num) { int majority; int cnt = 0; for(int i=0; i<num.size(); i++){ if ( cnt ==0 ){ majority = num[i]; cnt++; }else{ majority == num[i] ? cnt++ : cnt --; if (cnt >= num.size()/2+1) return majority; } } return majority; }
當然,這種演算法對於存在主元素的陣列是有效的,如:
A A A C C B B C C C B C C
它肯定能返回主元素C。但是,如果不存在主元素,那麼得到的結果就跟遍歷順序有關了。如:
A A A C C C B
如果是從左到右,那麼結果是B,如果是從右到左,那麼結果是A。
以上。