Given an array of integers, the majority number is the number that occurs more than half
of the size of the array. Find it.
要求:O(n) time and O(1) extra space
投票算法, 一般需要再遍历一遍,为防止不存在majority number的情况发生。
public class Solution {
/**
* @param nums: a list of integers
* @return: find a majority number
*/
public int majorityNumber(ArrayList<Integer> nums) {
if(nums.size() == 0) return -1;
int res = 0;
int tmp = 0;
for(Integer i : nums) {
if(res == 0) {
tmp = i;
}
if(i == tmp) {
res ++;
}
else {
res--;
}
}
return tmp;
}
}