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.
思路:如果一个数字在数组中超过半数,那么这个数字在int型32位每位上的计数肯定也超过一半,因此我们可以统计超过半数的bit位,然后利用位移方法算出总和,这个总和也就是要求的数字。
public int majorityElement2(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int res = 0;
int[] bits = new int[32];
int halfLen = nums.length / 2;
for (int num : nums) {
for (int i = 0; i < 32; i++) {
int bit = num >> i & 1;
if (bit > 0) {
bits[i]++;
if (bits[i] > halfLen) {
res += 1 << i;
}
}
}
}
return res;
}