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.數組
我的博客:http://www.cnblogs.com/wdfwolf3/。app
題目比較好理解,在含有n個元素的數組中找出出現次數超過⌊n/2⌋的元素,假設數組不爲空並且這個數是必定存在的。
dom
1.moore-voting算法ide
這個算法就是爲解決這個問題誕生的,主要思想就是找出一對不一樣的元素就去掉它們,最後剩下的必定是所找的元素。spa
class Solution { public: int majorityElement(vector<int>& nums) { int result=nums[0],count,i; for(i=1,count=1;i<nums.size();i++) { count+=nums[i]==result?1:-1; if(count>nums.size()/2) break; if(count==0) { count=1; result=nums[i+1]; i++; } } return result; } }
2.hashcode
遍歷數組,利用hash方式記錄元素出現的次數,當某個元素次數超過⌊n/2⌋時,即爲咱們要找的。
blog
class Solution { public: int majorityElement(vector<int>& nums) { unordered_map<int,int> m; int i; for(i=0;i<nums.size();i++) { if(++m[nums[i]]>(nums.size()/2)) return nums[i]; } return nums[0]; } };
3.sorting排序
對數組進行排序,因爲要找的元素超過半數,因此下標n/2的元素必定是它,這裏總數奇偶不影響,能夠本身舉例驗證一下。ip
class Solution { public: int majorityElement(vector<int>& nums) { //40ms sort(nums.begin(),nums.end()); return nums[nums.size()/2]; } };
4.randomization
隨機選取數組中的一個數,驗證它是否是超過半數的數字。時間最快,有一半概率選中,固然最壞的狀況比較糟糕,但這不重要,就像快速排序時間複雜度同樣。
class Solution { public: int majorityElement(vector<int>& nums) { srand(unsigned(time(NULL))); int tmp,i,count; while(true) { tmp=nums[rand()%nums.size()]; for(i=0,count=0;i<nums.size();i++) { if(tmp==nums[i]) count++; if(count>nums.size()/2) return tmp; } } } };
5.bit manipulation
就是把數字都做爲二進制處理,每一個二進制位上的n個bit相加看是否大於n/2,大於的話這一位上是1,小於的話就是0,把32位都這麼處理完就知道結果是多少了。
class Solution { public: int majorityElement(vector<int>& nums) { int i,j,count,major=0; for(i=0;i<32;i++) { for(j=0,count=0;j<nums.size();j++) { if((nums[j]>>i&1)==1) count++; } if(count>nums.size()/2) major+=(1<<i); } return major; } }
6.分治
處理這種問題均可以嘗試下分治方法,這道題也能夠不過感受太麻煩,就不寫了。