LintCode-Majority Number

时间:2023-03-08 17:13:42

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

For [1, 1, 1, 1, 2, 2, 2], return 1

Challenge

O(n) time and O(1) space

Solution:

 public class Solution {
/**
* @param nums: a list of integers
* @return: find a majority number
*/
public int majorityNumber(ArrayList<Integer> nums) {
if (nums==null || nums.size()==0) return -1;
int len = nums.size(); int cur = nums.get(0);
int count = 1;
for (int i=1;i<len;i++){
if (cur!=nums.get(i)){
count--;
if (count==0){
cur = nums.get(i);
count=1;
}
} else {
count++;
}
} return cur;
}
}