leetcode - majority elements
给定size 为n的数组,查找出主元素,就是出现次数大于n/2次的元素。
1.
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;}
2.
class Solution { public: int majorityElement(vector<int>& nums) { int ret = nums[0]; int count = 1; for(int i = 1; i < nums.size(); i ++) { if(nums[i] == ret) count ++; else { count --; if(count == 0) { ret = nums[i]; count = 1; } } } return ret; } };
3. Moore's voting algorithm
int majorityElement(vector<int> &num) {
int majorityIndex = 0;
for (int count = 1, i = 1; i < num.size(); i++)
{
num[majorityIndex] == num[i] ? count++ : count--;
if (count == 0) {
majorityIndex = i;
count = 1;
}
}
return num[majorityIndex];
}
4.
class Solution { 2 public: 3 int majorityElement(vector<int> &num) { 4 5 int count = 0; 6 7 for(;;) { 8 if(num.size() == 1) 9 return num[0]; 10 else { 11 int i = rand() % (num.size() - 1); 12 for(int j = 0; j < num.size(); j++) { 13 if(num[j] == num[i]) 14 count++; 15 } 16 if(count > (num.size() / 2)) 17 return num[i]; 18 else { 19 count = 0; 20 continue; 21 } 22 } 23 } 24 }5.int my_cmp(int a,int b){return a > b;}int Solution::majorityElement(vector<int> &num){sort(num.begin(),num.end(),my_cmp);return num[num.size()/2];}