LeetCode:Majority Element

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值