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.
找数组中元素个数超过一半的那个元素,采用位方法,对每个数转换为2进制,累加每一位上取值是1的值。
public:
int majorityElement(vector<int> &num) {
int len = num.size();
if (len < 3) return num[0];
int half = len/2;
int bit_ct[32];
for (int i=0; i<32; ++i) bit_ct[i] = 0;
for (auto n:num){ // count the number of 1 occured on each bit position
for (int i=0; i<32; ++i){
if (n%2) ++bit_ct[i];
n >>= 1;
}
}
int ans = 0;
for(int i=31; i>=0; --i){
ans <<= 1;
if (bit_ct[i]>half) ++ans;
}
return ans;
}
};