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.
这个问题的解法有很多,但是需要受时间复杂度的限制,并且条件中有n/2,利用这个可以有O(n)的解法。
class Solution {
public:
int majorityElement(vector<int> &num) {
int ncount =0;
int elem = 0;
for(int i=0;i<num.size();i++)
{
if(ncount == 0)
{
elem = num[i];
ncount = 1;
}
else
{
if(elem == num[i])
ncount++;
else
ncount--;
}
}
return elem;
}
};
自己写了暴力求解的方法:
int ncount(int a, vector<int> v)
{
int n=0;
for(int i=0;i<v.size();i++)
{
if(a==v[i])
n++;
}
return n;
}
int mainElement(vector<int> v)
{
int m;
int fre;
int maxfre,maxelem;
for(int i=0;i<v.size();i++)
{
int a = v[i];
fre = ncount(a,v);
if(i ==0)
{
maxfre = fre;
maxelem = a;
}
else
{
if(maxfre < fre)
{
maxfre = fre;
maxelem = a;
}
}
}
return maxelem;
}
也可以使构造数据结构来解:
typedef struct node
{
int key;
int num;
node* next;
}*Link;
Link creatNode()
{
Link newnode = new node;
if(newnode != NULL)
{
newnode->num = 0;
newnode->next = NULL;
}
return newnode;
}
int main()
{
int a[] = {1,1,2,3,4,5,1,6,7,3,4,3,3,3,3,2};
vector<int> v(a,a+sizeof(a)/sizeof(int));
print(v);
cout<<majorityElement(v);
cout << "Hello world!" << endl;
cout<<"max is:"<<mainElement(v);
/*
Link head = NULL;
Link current = head;
bool flag;
for(vector<int>::iterator it = v.begin(); it!=v.end(); it++)
{
flag = true;
for(current = head;current!=NULL;current=current->next)
{
if(current->key == *it)
{
current->num++;
flag = false;
break;
}
}
if(flag)
{
Link newnode = creatNode();
newnode->key = *it;
newnode->num++;
newnode->next= head;
head = newnode;
}
}
for(current=head;current!=NULL;current=current->next)
{
cout<<current->key<<' '<<current->num<<'\n';
}
for(current=head;current!=NULL;current=current->next)
delete current;
*/
return 0;
}