# An easy way to solve the problem ( 24ms )

• Every number in the vector votes for itself, the majority number gets the most votes. Different number offsets the votes.

``````int majorityElement(vector<int> &num) {

int vote = num[0];
int count = 1;
int size = num.size();
//vote from the second number
for( int i = 1; i < size; i++ )
{
if( count == 0 ) { vote = num[i]; count++; }
else if( vote == num[i] )	count++;
else count--;
}
return vote;
}``````

• nice solution

• elegant ideas!

• I've tested the solution on my own, and I found that this solution does not return correct result for some cases. e.g. {3,1,3,2,4} returns 4
basically when there is a continuous stream of unequal number, the result will be the last number appears, instead of the majority number.

• Hi, thanks. The question says, The majority element is the element that appears more than ⌊ n/2 ⌋ times, maybe your test case is not right.

• test this case:

3 1 3 2 4 3

I think this is wrong

• 3 should appear more than 3 times ( not include 3

• if we are working on JAVA than we have to change the size() method to length variable.

• what a smart solution!

• The solution works under the assumption that:

there must be a majority element (more than the half).

If we can not sure whether it contains one OR the definition of majority element is not 'more than the half', the solution will not work. We can find the median with O(N) time for the former problem.

• I agree. The code is tricky, but not robust.

• Because there is no majority number in your example array

• Note that:

element that appears more than ⌊ n/2 ⌋ times

• genius solution~

• I test this solution, it don't work correct,when I input [1,2,3,3,1,1],is output 3

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