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.
给定size 为n的数组,查找出主元素,就是出现次数大于n/2次的元素。你可以假定数组非空,而且主元素一定存在。
class Solution { public: int majorityElement(vector<int>& nums) { map<int, int> im; for (int i = 0; i < nums.size(); ++i){ map<int, int>::iterator it = im.find(nums[i]); if (it == im.end()) { im[nums[i]] = 1; } else { im[nums[i]]++; } if (im[nums[i]] > nums.size()/2) { return nums[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。
class Solution { public: int majorityElement(vector<int>& nums) { int n = nums.size(); sort(nums.begin(),nums.end()); return nums[n/2]; } };
#include<iostream> #include<vector> #include<algorithm> #include<map> using namespace std; int major(vector<int>); int main() { vector<int>a = { 1, 2, 3, 4, 2, 2, 5, 2, 2, 2, 2, 2, 2 }; cout << major(a) << endl; system("pause"); return 0; } int major(vector<int> a) { /*sort(a.begin(), a.end()); return a[a.size() / 2];*/ /*map<int, int> m; for (int i = 0; i < a.size(); i++) { if (m.find(a[i]) == m.end()) { m[a[i]] = 1; } else { m[a[i]]++; } if (m[a[i]]>a.size() / 2) return a[i]; }*/ //标志位想减法 可以判断出现次数做多数 int major; int num = 0; for (int i = 0; i < a.size(); i++) { if (num == 0) { major = a[i]; num++; } else { if (major != a[i]) num--; else { num++; } } if (num > a.size() / 2) return major; } }