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;
}
};
本文介绍了一种通过位操作解决数组中寻找元素个数超过数组长度一半的元素的方法。该方法将数组中的每个元素转换为二进制形式,并累加每一位上出现1的次数,从而找出满足条件的元素。
525

被折叠的 条评论
为什么被折叠?



