[LeetCode] Majority Element
Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more? n/2 ?Times.
You may assume that the array is non-empty and the majority element always exist in the array.
Solution:
1. Use a map to record the number of occurrences of each number. If the count of a certain number is greater than n/2, this number is returned.
class Solution {public: int majorityElement(vector
&num) { int len = num.size(); map
count; for(int i=0; i
len/2){ return num[i]; } } return 0; }};
2. For a sort array, if the mode number exists, the mode number must be the number in the middle.
class Solution {public: int majorityElement(vector
&num) { std::sort(num.begin(), num.end()); return num[num.size()/2]; }};
3. Voting algorithm. You can think of a man on the stage to win the game. If the man on the stage wins the same number of victories, he will step down and the man who finally defeated him will go on stage. The crowd must be the final winner. This algorithm takes the least time.
Class Solution {public: int majorityElement (vector
& Num) {int len = num. size (); if (len = 0) {return 0;} int candidate = num [0]; int count = 1; for (int I = 1; I
4. Bit algorithm. Considering that each number can be expressed in a 32-bit binary representation, each bit of each number is counted as 1. If the count of a binary bit is greater than n/2, there must be many contributions. This method is very novel. Although it is not as fast as the voting algorithm, it is just a matter of thinking. Here, the first method defines the map
Count: the default value of each newly added key value is 0, but for the int array type, each array is initialized to a random value. Therefore, use the memset function.
Class Solution {public: int majorityElement (vector
& Num) {int len = num. size (); if (len = 0) {return 0;} int bitCount [32]; memset (bitCount, 0, 32 * sizeof (int )); for (int I = 0; I
Len/2) // If the I-th digit is greater than half of the count, the contribution of the number of rows is certainly result + = (int) pow (2, I );} return result ;}};