zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    【bzoj4240】有趣的家庭菜园
    「洛谷 P1801」黑匣子
    「SDOI 2009」Elaxia的路线
    NOIP 2016【蚯蚓】
    NOIP 2014【斗地主】
    尺取法
    POJ 3169 Layout
    51nod【1196】字符串的数量
    51nod1671【货物运输】
    hihocoder1075【开锁魔法】
  • 原文地址:https://www.cnblogs.com/lingyi1111/p/5907398.html
Copyright © 2011-2022 走看看