Given an array of integers, the majority number is the number that occurs more than half
of the size of the array. Find it.
Example
Given [1, 1, 1, 1, 2, 2, 2]
, return 1
Challenge
O(n) time and O(1) extra space
public class Solution {
/**
* @param nums: a list of integers
* @return: find a majority number
*/
public int majorityNumber(ArrayList<Integer> nums) {
// write your code
int res=nums.get(0);
int count=1;
for(int i=1;i<nums.size();i++){
if(count>0){
if(res==nums.get(i))
count++;
else
count--;
}
else{
res=nums.get(i);
count=1;
}
}
return res;
}
}