LintCode-Majority Number
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:
1 public class Solution { 2 /** 3 * @param nums: a list of integers 4 * @return: find a majority number 5 */ 6 public int majorityNumber(ArrayList<Integer> nums) { 7 if (nums==null || nums.size()==0) return -1; 8 int len = nums.size(); 9 10 int cur = nums.get(0); 11 int count = 1; 12 for (int i=1;i<len;i++){ 13 if (cur!=nums.get(i)){ 14 count--; 15 if (count==0){ 16 cur = nums.get(i); 17 count=1; 18 } 19 } else { 20 count++; 21 } 22 } 23 24 return cur; 25 } 26 }