169. Majority Element 破解思路

来源:互联网 发布:网络选修课刷课软件 编辑:程序博客网 时间:2024/06/06 07:36

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.

看到这个题目首先想到的是一种暴力破解法 利用 两个指针和sort函数进行解题 ,思路是 首先进行排序 接着统计每个数字出现的次数,二话不说上代码:

class Solution {public:    int majorityElement(vector<int>& nums) {        int n=nums.size();        sort(nums.begin(),nums.end());        vector<int>::iterator it;        int count=1;        for(it=nums.begin();it<=nums.end();it++)        {            if(*it==*(it+1))            {                count++;            }            else            {                if(count>n/2)                {                  return *it;                                   }                count=1;            }        }     }
初刷用了40ms,后来想到了c++ 特有的map<int,int> 容器,对每个数记录一个count ,代码如下

class Solution {public:    int majorityElement(vector<int>& nums) {        int n=nums.size();            vector<int>::iterator it;            map<int,int> mapint;    map<int,int>::iterator lt;    for(it=nums.begin();it<nums.end();it++)    {        lt=mapint.find(*it);        if(lt==mapint.end())        {            // mapint.insert( pair <int, int>  ( *it, 1 ) );两种方法都可以给mapint加入一个新的键值对            mapint[*it]=1;            if(n==1)              {                  return *it;              }        }        else{                                    (*lt).second++;            if( (*lt).second>n/2)            {                return *it;            }        }    }    }
此刷是32ms,我顿觉可能我的能力就到这了,后来百度了一下该题目,真是有神解呀,moore voting algorithm,每次找出一对不相同的相邻数值,则都删掉,最后剩的那个就是要找的majority number,但是我们此时不用直接删除,只需要找出一个删到某一时间时,count最大的那个(好吧,我知道我表达不清楚)还是上代码吧

class Solution {public:    int majorityElement(vector<int>& nums) {      vector<int>::iterator it;     int majority=0;     int count=0;     for(it=nums.begin();it<nums.end();it++)     {         if(count==0)         {             majority=*it;             count++;         }         else{             if(majority!=*it)             {                 count--;             }             else             {                 count++;             }         }                  }     return majority;          }   };
此刷20ms



0 0
原创粉丝点击