[C++] Moore Majority algorithm (26s)


  • 3
    4
    class Solution 
    {
    public:
    int majorityElement( vector< int > & num ) 
    {
        	int count = 1;
    	    int target = num[0];
    
            for( int i = 1; i < num.size(); ++i )
    		{
    			if( !count ) target = num[i];          // if( !count ) { target = num[i]; count = 1; continue; }
    			if( target == num[i] ) ++count;
    			else --count;
    		}
    		return target;
    }
    };

  • 0
    C

    i think u can return the target if count>= num.size()/2+1 from your for-loop statement


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.