leetcode之169. Majority Element

来源:互联网 发布:国家药监局数据库查询 编辑:程序博客网 时间:2024/05/20 04:10

原题:
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.

********************************我是一条分割线*************

class Solution{public:    int majorityElement(vector<int>& nums)    {        map  <int,int> m;        for(int i=0; i<nums.size(); i++)        {            m[nums[i]]++;        }        int resu=-1;        for(map<int,int>::iterator it = m.begin(); it != m.end(); it++)        {            if((*it).second*2 >= nums.size())            {                resu = (*it).first;                break;            }        }        return resu;    }};

测试程序

int main(){    int a[]={2,2,1,2,3,4,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,21,1,1};    vector<int > b(a,a+17);    int resu;    Solution s;    resu=s.majorityElement(b);    cout<<resu<<endl;    return 0;}

三天不动就手生。。。。。。。。。。。。。。也是醉了

0 0
原创粉丝点击