给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.
样例
给出数组[1,1,1,1,2,2,2],返回 1
挑战
要求时间复杂度为O(n),空间复杂度为O(1)
public class Solution {
/**
* @param nums: a list of integers
* @return: find a majority number
*/
//法一:O(32n)位操作。统计32位每一位1的个数多还是0的个数多,取个数多的为该位结果值。
public int majorityNumber(ArrayList<Integer> nums) {
int bit = 1;
int result = 0;
for(int i = 0; i < 32; i++) {
int count0 = 0;
int count1 = 0;
for(int j = 0; j < nums.size(); j++) {
if((nums.get(j) & bit) == bit) {//第i位为1
count1++;
}else {//第i位为0
count0++;
}
}
if(count0 < count1){//第i位1的数目多于0的数目,则该位应为1,否则为0
result = result ^ bit;
}
bit = bit<<1;
}
return result;
}
//法二: 分治法 Divide and conquer O(n)
//保持两个标记变量。一个统计值count初始为0,一个当前值cur。遍历整个数组,用x表示当前值。
//当count == 0时,设cur = x, count++。
//当count != 0时,若x == cur,则count++;若x != cur,则count--。
//最后返回cur。
public int majorityNumber(ArrayList<Integer> nums) {
int count = 0;
int cur = nums.get(0);
for(int i = 0; i < nums.size(); i++) {
if(count == 0) {
cur = nums.get(i);
count = 1;
}else {
if(cur == nums.get(i)) {
count++;
}else{
count--;
}
}
}
return cur;
}
}