版权声明:本文为博主原创文章,未经博主允许不得转载。
难度:容易
要求:
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
样例
给出数组[1,1,1,1,2,2,2],返回 1
思路:
/**
* @param nums: a list of integers
* @return: find a majority number
*/
public int majorityNumber(ArrayList<Integer> nums) {
// write your code
int count = 0;
int num = -1;
for(Integer i : nums){
if(count == 0){
num = i;
count++;
}else if(num == i){
count++;
}else{
count--;
}
}
return num;
}