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.
思路:可以参考快速排序的定位方法,参照任何一个元素,进行重新一次排序,之后相同的元素就相邻,既然这个元素多余总元素个数的n/2,那么遍历这个数组,对于此元素和n/2之后的元素相等,说明就是这个元素。
#include <iostream>
#include <vector>
using namespace std;
int majorityElement(vector<int> &num)
{
int i,j;
int key = num[0];
for(i=-1,j=0;j<num.size();j++)
{
if(num[j]<key)
{
i++;
swap(num[i],num[j]);
}
}
for(i=0;i<num.size()/2;i++)
{
key = num[i+num.size()/2];
if(num[i] == key)
return key;
}
}
int main()
{
int array[]={3,2,4,5,2,2,4,2,2,2,2,7};
vector<int> vec(array,array+sizeof(array)/sizeof(int));
cout<<majorityElement(vec);
system("pause");
return 0;
}
原文:http://blog.csdn.net/yusiguyuan/article/details/45007583