169. Majority Element----Array----Easy----20160925

题目:

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.

思路:

  数组中没遇到两个不相同的数字时,就把这两个数字都删除掉,最后留下的数字就是那个大多数。

代码1:

//////下面的代码提示超时  

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int len=nums.size();
                   int u=0; 

        if(len==1)
        {
            return nums[0];
            
        }
        
        int k=0;
        while(k<len-1 && nums[k]==nums[k+1])
        {
            k++;
        }
        if(k==len-1) return nums[0];
        
        int m=0;
        for(int p=0;p<len;p++)
        {
            if(nums[p]==0)
            m++;
        }
        if(m>len/2) 
        return 0;
        
        int i=0;
        int j=len-1;
        while(i<j)
        {
            if(nums[i]!=nums[j])
            {
                i++;
                j--;
                nums[i]=0;
                nums[j]=0;
            }
            else
            {
                if(nums[i]==nums[j])
                {
                    while(i<j)
                    {
                        if(nums[i]==nums[j])
                        {
                            i++;
                        }
                    }
                }
            }

         for( u;u<=len-1;u++)
         {
             if(nums[u]!=0)
             {
                 break;
             }
         }

            
        }
                 return nums[u];
    }
};

////////////////////////////////////////////

////////////////////////////////////////////

///////////////////////////////////////////

代码2 map做的  

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        map<int ,int> m;
        int len=nums.size();
        int result=-1;
        
        for(int i=0;i<len;i++)
        {
            m[nums[i]]++;
        }
        
        map<int ,int >::iterator it;
        for(it=m.begin();it!=m.end();it++)
        {
            if(it->second >len/2)
            {
                result=it->first;
            }
        }
        return result;
    }
};
原文地址:https://www.cnblogs.com/lingyi1111/p/5907398.html